Control the object's movement

I am currently working on quite complex project. Anyway, im not gonna go into deeper details. What I am stuck with is following function.

What I've got so far is basically a picture, and what I am trying to do is to set continuous movement to it, allow the user to control the directions of its movement by pressing "Up" , "Down", "Left " and "Right" key. The best example I can base my idea on is "Snake" game.

I don't have much of a code, however I am willing to upload it upon request.

Hopefully, you guys can help me.

Thank you.

So basically you need two velocity variables:
float xVelocity;
float yVelocity;

When the user presses 'Up' the yVelocity is increased to a number you have set. 'Down' and the yVelocity is decreased (from 0) by the same number that you set.

'Right' and you increase xVelocity 'Left' you decrease.

Everytime you release a key you reset that particular velocity back to 0.
So when they user releases the 'Up' key yVelocity is set to 0.

So every loop when you update your sprites on the screen you move the X position of the 'snake' by the xVelocity, and the Y position by the yVelocity.

So if xVelocity is negative (moving left) the 'snake' will move to the left (negative x positions), if xVelocity is positive the 'snake' is moving right.

So when no keys are pressed both velocities are 0 and the snake is completely still.

You can even multiply the xVelocity and yVelocity by the time elapsed since the last movement to make sure that the snake moves at the same speed on all machines.
Topic archived. No new replies allowed.