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

3 Answers

3

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.

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. :slight_smile:

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 Mathf.Approximately (f1, f2) exists for!

You can do a simple distance proximity check…

i.e

var distance = Vector3.Distance(transform.position, end);

if(distance < 0.1f)
  moving = false;