- Home /
Basic Lerp question
Hi everyone, I'm extremely new with Unity and scripting.
I have an object that when it apear I need it to go from world origin to the specific Vector3 (0,0,8)
But I can't seem to find the mistake I'm doing. This is the script that I wrote for the object. Is pretty simple:
{ public float speed;
void start ()
{
transform.position = Vector3.Lerp(transform.position, new Vector3 (0,0,8), Time.deltaTime * speed);
}
}
I also tried with a void awake and nothing...
Help! Anyone?
try giving speed a value like public float speed = 3. and also start needs to be capitalized like Start()
Also, put your lerp in Update() or use a coroutine since Start() is only ran once.
Answer by Curb · Mar 27, 2014 at 04:07 PM
The Start function will only execute on one frame. A lerp is usually used to animate an object over multiple frames. One way of doing this would be to make a coroutine:
IEnumerator MoveObject(float duration){
float t = 0;
Vector3 currentPos = transform.position;
Vector3 newPos = new Vector3(0,0,8);
while (t < 1){
t += Time.deltaTime / duration;
transform.position = Vector3.Lerp (currentPos, newPos, t);
yield return null;
}
}
Then call it from somewhere with:
StartCoroutine(MoveObject(3));
The 3 is the duration of the animation. You could build in even more parameters between the () of course.. such as the new position. But this should get you going. :)
This worked great!! It's exactly what I wanted. Can I ask you why the rutin is a IEnumerator? I thought that was for geting aligned a series of numbers.
it's an IEnumerator because it's a Coroutine. Any function with a yield statement is a coroutine. Don't forget to mark Curb's answer as correct :D
http://docs.unity3d.com/Documentation/$$anonymous$$anual/Coroutines.html
Your answer
Follow this Question
Related Questions
Unity freezing on Waitforsecond 1 Answer
How do I apply gravity, but only in the y-axis? 2 Answers