- Home /
Get an Object to move to a Position for a Fixed time
Hey, I am trying to get this object to move to "EndPoint". The code is working, I just don't want to set the speed it moves at, but the time it takes to reach its destination. Anyone got any ideas of how to fix this? Thank you in advance!
void Update ()
{
if(EndPoint != Vector3.zero)
{
myTransform.position = Vector3.MoveTowards(myTransform.position, EndPoint, Time.deltaTime * MuzzleVelocity);
}
if(myTransform.position == EndPoint)
{
Destroy(gameObject);
Debug.Log ("Destroyed Object");
}
}
Answer by yatagarasu · Dec 02, 2013 at 03:14 PM
Time and speed are easily interchangeable. You can take the distance to the destination divide it by time you want your object to move and you'll get the speed your object should move with.
Answer by MrVerdoux · Dec 02, 2013 at 12:01 PM
I use enumerators for this:
private float movementTime = 2;
private float lerpTime = 0.05f;
void Start(){
StartRoutine("MoveTo", new Vector3(1,0,0);
}
IEnumerator MoveTo(Vector3 destination){
float timeEllapsed = 0;
Vector3 origin = transform.position;
while (timeEllapsed < movementTime){
transform.position = Vector3.Lerp(origin,destination,timeEllapsed/movementTime)
timeEllapsed += lerpTime;
yield return new WaitForSeconds(lerpTime);
}
}
Haven´t tested particularlly this one, it might need you to fix it somewhere!
it is the amount of time that has passed since the coroutine began. It´s a local variable because you don´t have to use it anywhere, you just set the total amount of time.
Notice that in the begining ellapsedTime = 0
and every loop it will be a little bigger. In the end, the condition to get out of the loop (and then finish the coroutine) is that the ellapsed time is bigger than the total time of the movement.
And how do you get to move from any point to any other in a certain amount of time? Well, I used a linear interpolation. That is (Notice that linear interpolation is normally named "Lerp"):
float LinearInterpolation(float from, float to, float t){
return from*(1-t) + to*t;
}
I used the same thing for a Vector3
. If you want a soft movement you might want to use a different kind of interpolation.
You haven't defined the variable ellapsedTime in the code though and I don't know what I have to put...do you mean timeEllapsed? In this case there is an error in the code.