Problems with Lerp.

Hello! I am not an expert in coding but I can do simple stuff such as if statements and stuff like that, but then I thought I should learn to do more advanced things, so I made a little game that uses lerp, but I am having a problem with lerp, I am trying to make a game where if you click the ground you go down, and go back up in one second (Don’t ask why), but it isn’t smooth and it doesn’t come back up when one second has passed, it instead goes down more. It is my first time using lerp by the way.

var clicks = 0;
var lerpPosition : float = 0.0f;
var lerpTime : float = 5.0f;
var start : Vector3 = new Vector3(0, 0.9070835, 0);
var end : Vector3 = new Vector3(0, 0.1879287, 0);

function OnMouseDown() {
if (Input.GetKey ("mouse 0")) {
print ("Push Up!");
clicks = clicks + 1;
lerpPosition += Time.deltaTime/lerpTime;
Camera.main.transform.position = Vector3.Lerp(start,end,lerpPosition);
yield WaitForSeconds(1);
lerpPosition += Time.deltaTime/lerpTime;
Camera.main.transform.position = Vector3.Lerp(end,start,lerpPosition);
}
}

Thanks for any help, also sorry for bad grammar, I am really tired.

  • Always use ‘#pragma strict’ at the top of your files. It will prevent some inefficient code and also force some buts to be caught at compile time rather than runtime.
  • lerpPosition should be a local variable to OnMouseDown().
  • Your current code has a problem in that if the user clicks on object while the object is moving, then you will create two coroutines that will fight each other.
  • Lerp() needs to be executed across a number of frames. Right now, you only Lerp() twice per click (one up and one down).

Here is your code modified to fix these problems:

#pragma strict
 
var clicks = 0;
var lerpTime : float = 5.0f;
var start : Vector3 = new Vector3(0, 0.9070835, 0);
var end : Vector3 = new Vector3(0, 0.1879287, 0);

var lerping = false;
 
function OnMouseDown() {
	if (!lerping) {
       lerping = true;
		var lerpPosition : float = 0.0f;
		print ("Push Up");
		clicks = clicks + 1;
		while (lerpPosition <= 1.0) {
			lerpPosition += Time.deltaTime/lerpTime;
			Camera.main.transform.position = Vector3.Lerp(start,end,lerpPosition);
			yield;
		}
		yield WaitForSeconds(1);
		lerpPosition = 0.0;
		print ("Pull Down");

		while (lerpPosition <= 1.0) {
			lerpPosition += Time.deltaTime/lerpTime;
			Camera.main.transform.position = Vector3.Lerp(end,start,lerpPosition);
			yield;
		}
		Camera.main.transform.position = start;
       lerping = false;
	}
}