- Home /
How to make a gameObject move from it's current position in a different direction after a set amount of time
EDITED:
Hello everyone.
I have a sphere that I am moving using rigidbody.velocity
. I would like to after a set time in this case 5 seconds tell the sphere to move in a new direction. For example the sphere starts moving to the left,after 5 seconds are up the sphere starts moving upwards. So after every 5 seconds that pass the sphere keeps changing it's movement direction.
In order to achieve this I was thinking that I could keep track of the sphere's position throughout its travel time.Then when the seconds are up I assign the position it is at as the new position.Another words I want to have the sphere take it's current position as the new starting point from which it moves off.
I tried to do this by tracking the position of the sphere at run time and the after 5 seconds are up assigning it to a new variable.But that has gotten me nowhere.
This is my timer code:
function LateUpdate ()
{
print("late update");
ParticleMovement();///Function that controls sphere movement
if(movementTimer > 0)
{
movementTimer -= Time.deltaTime;
print(movementTimer);
}
if(movementTimer <= 0)
{
ParticleMovement();//I'm calling the movement function here when timer
//reaches zero so that the particles direction
//is chosen again.
movementTimer = newTimer;//Reset the timer back to 5 seconds every time
}
}
All hints are welcome :D
Thank you.
For one don't compare Vectors directly for equality, for the same reason you don't compare floats for equality. Try Vector3.Distance(newPosition, CurrentPosition) < 0.01 or something.
Secondly why do you need this check at all? Don't you want to change direction after 5 seconds regardless, in which case this test is pointless?
You mention a few times ' set the current position of the sphere as it's origin point '... this doesn't make sense to me as the position of a primitive sphere will always be it's origin point.
$$anonymous$$aybe post some more of your code for context and try explaining exactly what you want again, just so we can be perfectly clear.
Answer by delpontej · Nov 09, 2013 at 08:43 PM
Your newPosition and currentPosition values probably will never be exactly the same value, which is what is being tested in your example. Especially, if the movement is performed overtime. In stead of checking if newPosition is currentPosition, I'd suggest calculating the distance between the two points, and if the returned distance is less than an acceptable margin the currentPosition is 'close enough' to the new position. From there if you really want you could snap the currentPosition to your newPosition if needed.