- Home /
Check if object is moving towards a point
Greetings! I'm looking to find a solution to check if an object is moving towards a vector3 position (or another object's position). Basically if the distance is decreasing, return true, else if it's increasing, return false.
Answer by nt314p · Aug 07, 2017 at 03:24 PM
Thanks to Elthen for giving the Vector3.distance idea.
Put this code at the top:
public float dist;
And this function at the bottom:
public bool CheckDirection () {
float distTemp = Vector3.Distance(destination.position, transform.position);
if (distTemp < dist) {
dist = distTemp;
return true;
} else if (distTemp > dist) { // rigorous checking
dist = distTemp;
return false;
}
}
Make sure the function is being called constantly (I am assuming it will be)
Basically it checks if the distance last frame was further or closer than the distance this frame, and then returns the desired value.
Tell me if it doesn't work and I can see what I can change.
Sorry if you wanted it in Java, but hopefully you get the main idea of the code.
Yes this is exactly what I needed, but if we're returning true or false, we wouldnt reach the last line. Thank you so much for the help!
O$$anonymous$$, I changed the code so that the dist = distTemp will run if you haven't figured out a workaround already (I'm sure you have).
Answer by Elthen · Aug 07, 2017 at 01:49 PM
Hmmm not sure if this would help; anyway, you could keep track of the distance by using Vector3.Distance() inside an Update() to check the distance between two Vector, like so:
if (Vector3.Distance(destination.position, transform.position) > 0.5f)
{
//do something
}
See: https://docs.unity3d.com/ScriptReference/Vector3.Distance.html