- Home /
Stop a Lerp from looping
The lerp on this script runs every update, how do I tell it to stop when its reached its lerp end point?
var toggle : int = 1;
var moving : boolean = false; //uses toggle to become true or false
var speed : float = 1; //speed of movement
var start : Vector3;
var end : Vector3;
function Update () {
if(moving == true) {
start = Vector3(transform.position.x,transform.position.y,0);
end = Vector3(transform.position.x,transform.position.y,1);
}else{
start = Vector3(transform.position.x,transform.position.y,1);
end = Vector3(transform.position.x,transform.position.y,0);
}
//Moves Gameobject
if(moving) {
transform.position = Vector3.Lerp(start, end, Time.deltaTime*speed);
}
//Controls Active from toggle - Active starts false
if(toggle == 1) {
moving = false;
}else{
moving = true;
}
}
function OnMouseDown() {
toggle = (toggle + 1)%2;
}
//GameObejct need Collider
Answer by DaveA · Mar 20, 2012 at 05:21 AM
One way is to use Mathf.Approximately on x,y,z to see if the current position is near the destination. Or you can use a distance check to see if it's close enough.
Answer by Kleptomaniac · Mar 20, 2012 at 06:37 AM
Why not just add on to your if statement:
if(moving && transform.position != end) {
That will stop the lerp from running when the transform.position of the gameObject is equal to the end point. :)
Hope that helps, Klep
Checking if two floating point values are identical is not a very efficient thing to do, and in fact they might never ever match, or take longer than usual to match.
Hmm, yeah true ... @DaveA 's answer is probably best then. :P
Well, that's what
$$anonymous$$athf.Approximately (f1, f2)
exists for!
Answer by Meltdown · Mar 20, 2012 at 06:43 AM
You can do a simple distance proximity check..
i.e
var distance = Vector3.Distance(transform.position, end);
if(distance < 0.1f)
moving = false;
Thanks guys that gives me lots of options, I did want to add a collision to the movement, so if it bumps into another object it stops and moves back to its start point (which will always be transform.position.x,transform.position.y,0).
Your answer
![](https://koobas.hobune.stream/wayback/20220613065325im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
ricreate Lerp function 2 Answers
Vector3.lerp doesn't work 1 Answer
Problem with Vector3.Lerp 1 Answer
Move Object Forward Click, Move Object Back again on another Click 0 Answers