- Home /
Distance won't work
Help!!!
This script was supposed to assign a specific distance when clicking an npc to start a connversation. If "dist" is less than "fixdist", the character can click to the npc.
This code works fine in my other event, I copy pasted it from there.
Here is the code:
private var trgtObjct : Transform;
function Start(){
trgtObjct = GameObject.FindGameObjectWithTag("Player").transform;
}
function npcTalk(){
var fixdist = 100.3872;
if (trgtObjct!= null)
{
var dist : float = Vector3.Distance(trgtObjct.position, this.transform.position);
if (dist <= fixdist)
{
OnMouseDown();
}
else
print("Lumapit ka");
}
sorry for the bad english.
How do you know the problem is distance? Anything could be causing the problem. $$anonymous$$aybe print dist
right after you compute it, to check? It is printing "Lumapit ka" after each click?
because the player can still click to the npc even if the distance is greater than the given variable(fixdist). I just copy pasted this from the other javascript file, which is also on the same scene as this. The code works fine on the other script. The print"Lumapit ka", doesn't affect the code, i put comment/remove that line from the script, still doesn't work
He was asking about "Lumapit ka" to see whether this code segment was ever executed, not because it could cause a bug.
sorry, that code segment didn't appear so i removed it from the script.
But it was a good debug message ;-) If it was never printed, it means that either dist is never > fixdist - or that there was no object "Player" found, or that npcTalk() is never called. How/where do you call npcTalk()?
Also, a fixdist of 100.3872 sounds rather large. Are your scene dimensions really this big? Are your models in centimeters?
Answer by Wolfram · Feb 03, 2013 at 04:40 PM
If the distance is smaller, you are explicitly calling OnMouseDown(). However OnMouseDown() is being called unconditionally (well, the condition is that the mouse is over the object's Collider when clicking) by the game engine on mouse click anyway, so your approach does not work this way.
Use your own function to place your code in that should be executed when you have a "valid" click, and don't call it "OnMouseDown".
So I'll just have to put it on different function and not name it as "On$$anonymous$$ouseDown". Sorry I'm still new to javascript and unity, what do you mean by "valid" click??
Yes, that's what I meant. With valid I meant the conditional click you are trying to implement, where dist