- Home /
Difficulty with Vector2 Lerp, object jumping, not moving
Hello friends, I'm trying to make my game object move from its current start position to where the user clicks on the screen. I've used a ScreenPointToRay to help find the position of where they click.
The basic problem I'm having is I'm unsure how to manipulate the Lerp function to smoothen out my movement. Right now, the game object is simply jumping to where the user clicks. Its not translating or moving, just appearing suddenly. I suspect the "t" variable of the Lerp function is something to do with it, but I don't understand what it means. Any ideas? Thanks
function Update () {
var cube = GameObject.FindWithTag("Cube");
if(Input.GetMouseButtonDown(0)){
var startPos = cube.transform.position;
var ray : Ray = camera.main.ScreenPointToRay (Input.mousePosition);
var selected : RaycastHit;
Physics.Raycast(ray, selected);
cube.transform.position = Vector2.Lerp(startPos, selected.point, Time.time);
}
}
Answer by Eric5h5 · Jun 29, 2011 at 10:14 PM
That's not how Lerp is used; it's not a function that makes things happen over a period of time. Lerp returns a value immediately. (Also, you don't want Vector2, which only has two vectors. You need 3 vectors for 3D space.) In order to make things appear to happen over a period of time, you call Lerp repeatedly, while gradually advancing the third parameter from 0.0 to 1.0. See here for a coroutine that moves an object from one point to another.
Thanks eric. I'm actually only translating on the X and Y axis, so I don't need Vector3. I'm using your $$anonymous$$oveObject function successfully.
Answer by Skjalg · Jun 29, 2011 at 10:14 PM
When using Vector2.Lerp the time (the third variable) needs to be a float between 0 and 1. Using Time.time after 15 seconds of gametime will result in the number 15 being thrown in there, and will ultimately result in the object just popping up at the end position.
What you probably want to do is using Time.deltaTime multiplied by some speed factor.
You usually don't want to use Time.deltaTime multiplied by some speed factor; see here: http://answers.unity3d.com/questions/14288/can-someone-explain-how-using-timedeltatime-as-t-i.html
Your answer
Follow this Question
Related Questions
Get RaycastHit Local Coords (C#) 1 Answer
Collisions while using Vector2.Lerp 0 Answers
Moving Object using Raycast / Lerp C# 2D 0 Answers
Problem with lerping Y axis 0 Answers
[C#] can someone give me a detailed explanation of lerp 1 Answer