Need some help, How do I move an object upward and downward. Like 5 secs it will go upward and after 5 secs it will go downward, continue loop ?
Thank you
One way :
Use 2 variables - yDirection (initially set to -1) and movementTimer, set to 0 at the beginning of the scene.
- Change object’s y position by yDirection * TimeDelta() * <speed in pixels per second>.
- Add TimeDelta() to movementTimer.
- if movementTimer > 5
{
reduce movementTimer by 5
yDirection = yDirection * -1
} - repeat
Edit
Actually, that may not be the best way - the object won’t turn at the same spot every time.
Try the following instead:
Use 3 variables - yDirection (initially set to -1), yOriginal (initial Y co-ordinate of the object) and movementTimer, set to 0 at the beginning of the scene.
- Add TimeDelta() * yDirection to movementTimer.
- If movementTimer > 5 or movementTimer < 0
{
Set yDirection = yDirection * -1
Add TimeDelta() * yDirection to movementTimer.
} - Set object’s y co-ordinate to yOriginal + movementTimer * <speed in pixels per second>.
- repeat
And if you’d like the motion to be smooth acceleration and deceleration, then look into easing functions.