- Home /
Way to move object over time?
Hi, I have a checkpoint object that im trying to move up a bit when the player activates it.
When said player collides with the trigger, i would want the object to slowly move up a certain height(lets say 5)
Any ideas on how to do this? Ive tried a few things but they resulted in it looking like a regular transform.Translate, which is not what i needed.
Any help would be greatly appreciated! Thanks again.
Answer by ArkaneX · Nov 11, 2013 at 09:34 AM
Take a look at Vector3.Lerp example.
Thxs for your help! ended up using a Vector3.$$anonymous$$oveTowards with a cube object as the target, works like a charm!
Answer by Lakeffect · Feb 25, 2016 at 08:27 AM
Move any object to any place at any speed (units/seconds) or in any time -- all done without using Update:
StartCoroutine (MoveOverSeconds (gameObject, new Vector3 (0.0f, 10f, 0f), 5f));
public IEnumerator MoveOverSpeed (GameObject objectToMove, Vector3 end, float speed){
// speed should be 1 unit per second
while (objectToMove.transform.position != end)
{
objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position, end, speed * Time.deltaTime);
yield return new WaitForEndOfFrame ();
}
}
public IEnumerator MoveOverSeconds (GameObject objectToMove, Vector3 end, float seconds)
{
float elapsedTime = 0;
Vector3 startingPos = objectToMove.transform.position;
while (elapsedTime < seconds)
{
objectToMove.transform.position = Vector3.Lerp(startingPos, end, (elapsedTime / seconds));
elapsedTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
objectToMove.transform.position = end;
}
This works really well. However I had to change Line 18 to
objectTo$$anonymous$$ove.transform.position = Vector3.Lerp(startingPos, end, (elapsedTime / seconds));
and Line 22 to
objectTo$$anonymous$$ove.transform.position = end;
Otherwise the object running the script will be moved ins$$anonymous$$d of the intended object.
That's absolutely right! Thanks for the correction. I went ahead and edited it and referenced the change in the revision summary. Good catch!
These work perfectly for me, except one thing. Whenever it gets to the end it is rough, it is almost like someone slam$$anonymous$$g on breaks in a car. Does anyone know how to make it more smooth?