- Home /
Help With Lerping, not larping
so i need to lerp an object between a position off and on camera. With the code below, it lerps off camera right away, then with i hit the space bar to move the camera on screen it jumps right to the on screen position, rather than smoothly lerping on camera. Sorry about the redundant and messy code, im a beginner. Thanks!
var theX : float; var theZ : float; var theMain : GameObject; var mini : GameObject; var theY : float = 1.187029; var newX : float; var newZ : float; var cur : Vector3; var pre : Vector3; newX = theX + 1.257045; newZ = theZ - 1.179323; cur = Vector3(4.839913, -0.5300512, newZ); pre = Vector3(newX, -0.5300512, newZ);
function Update () { theMain = GameObject.Find("Main"); mini = GameObject.Find("mini"); theX = theMain.transform.position.x; theZ = theMain.transform.position.z; var exe = Input.GetKey("space");
if (exe)
{
transform.localPosition = Vector3.Lerp(pre, cur, Time.time);
mini.camera.depth = -2.0;
}
if (!exe)
{
transform.localPosition = Vector3.Lerp(cur, pre, Time.time);
mini.camera.depth = 1.0;
}
}
LOL @ the title, tell me that was you $$anonymous$$ike.
I'll bet the OP named it "Help with larping", and $$anonymous$$ike fixed it. LOL.
Answer by Mike 3 · Apr 01, 2011 at 06:43 PM
You either need to store the current t value (i.e. 0->1 of how far you are into the lerp) and increment that by Time.deltaTime, or you can use Vector3.MoveTowards, and move from the current position to the wanted position, instead of start to end
I'd go with the latter for ease of reading:
if (exe) { transform.localPosition = Vector3.MoveTowards(transform.localPosition, cur, Time.deltaTime * speed); mini.camera.depth = -2.0;
} else { transform.localPosition = Vector3.MoveTowards(transform.localPosition, pre, Time.deltaTime * speed); mini.camera.depth = 1.0; }
The speed value is how fast it'll move in meters per second, and needs declaring elsewhere
nailed it! The greatness of the unity answers community never fails me. Soooo good!
Answer by Owen-Reynolds · Apr 02, 2011 at 02:22 AM
Lerp's second input is a percent, from 0 to 1, with anything more than 1 counting as 1. Time.time
is the total seconds you've been running. So, all Time.time
by itself is good for is the first second after Play. To get smooth motion with Lerp, you'd have to use Time minus time when you last pressed space, divided by how many seconds you want it to take. MoveTowards
is easier.
Lerp can be used for a "fast at first, then slower" move. You run this every frame, and change newPos whenever you feel like it (the Camera scripts use this trick):
transform.position = Vector3.Lerp(transform.position, newPos, 0.03f);
The 0.03f (I use C#, so you may not need the 'f',) means to go 3% closer each frame. Making it smaller goes slower. Anything 0.1f of more (10% each frame) almost snaps it to newPos.
Your answer
![](https://koobas.hobune.stream/wayback/20220613120223im_/https://answers.unity.com/themes/thub/images/avi.jpg)