how to check when MoveTowards has finished
Hello,
I've got a small portion of code which does move a GameObject to a random destination (Specified by the target in the array). It all works fine, I just want to know how to check when the "MoveTowards" has finished, so I can find a new destination or target. The last pseudo 'if' statement is what I'm trying to achieve. Thanks a lot!
#pragma strict
var target : Transform[];
var isMoving : boolean = false;
var speed : float = 5.0f;
var newTarget : Transform;
function Update()
{
if(isMoving == false)
{
newTarget = target[Random.Range(0,target.length)];
isMoving = true;
}
transform.position = Vector3.MoveTowards(transform.position, newTarget.position, speed * Time.deltaTime);
if(MoveTowards has finished)
{
isMoving = false;
}
}
you could create your own Vector3.Approximately method, by just checking the x, y and z floats all return true from $$anonymous$$athf.Approximately, or you could save the start position and work out how long it will take to travel the distance given your speed (doesn't work if you have variable speed), or you could use lerp ins$$anonymous$$d and check when your t value given is more than or equal to one?
HYPERSAVV, superb answer. The answer was staring me right in the face... Thanks for your time! Works perfectly. I'll mark your comment as a chosen answer if you convert it. Thanks.
Answer by HYPERSAVV · Jan 08, 2015 at 11:22 PM
Just check to see if transform.position equals newTarget.position
Answer by Juice-Tin · Jan 08, 2015 at 11:36 PM
if(Vector3.Distance(transform.position, newTarget.position) < 0.1f){
//It is within ~0.1f range, do stuff
}
Since it moves speed * Time.deltaTime
units per frame, you could check if the distance is smaller than that to have a more precise result.
if(Vector3.Distance(transform.position, newTarget.position) < speed * Time.deltaTime){
//do stuff
}
Another cool thing you can do is make your own $$anonymous$$oveTowards function that returns whether it reached that position or not. This is good because you will get the result in the same frame as it overshoots the destination, and not one frame after:
private bool $$anonymous$$oveTowards(Transform t, Vector3 target, float speed) {
if (Vector3.Distance(transform.position, target) < speed) {
t.position = target;
return true;
} else {
t.position = Vector3.$$anonymous$$oveTowards(t.position, target, speed);
return false;
}
}