I use dist() to get the distance between the player and the object that is clicked. But the result is varying a lot everytime I click the object. Is this a known bug. Is there another way to get the distance that is more reliable?
(EDITED)
function OnMouseUp () {
dist = Vector3.Distance(gameObject.transform.position, GameObject.FindWithTag("Player").transform.position);
Debug.Log(dist);
if(dist < 1.5) {
// Do stuff
} else { globals.msgTxt += "You're to far away!
"; }
}
The script is attached to resource nodes and is executed everytime the gameObject is clicked. But even if the player stands still and I click the same node several times, the distance is variable (see screenshot).
There is no bug, it’s very basic math…Vector3.Distance is just (a-b).magnitude and is 100% reliable. If it’s returning a variable result then that always means the distance between the two points is variable. So if you’re not expecting that then you need to look elsewhere for the problem.
As Eric5h5 mentioned Vector3.Distance is reliable, the distance is variable likely because the dist returned is choosing a different object each time you click.
Try assigning the script to just one object and it should return one value.
or better yet have it return the name of the object clicked
Thanks for the help guys. It look like the dist() is correct afer all
I found out that I had added Rigidbody component to my player character (in addition to Character controller, Third person controller, Third person camera).
When I removed the Rigidbody, the script returned the same distance every time!? I don’t understand why, but so it is.
Bunny83: You might wanna try to add Rigidbody component to your character in your test game and see if you get the same wierd result