# Moving in a direction determined by a sprite's angle of rotation

## Recommended Posts

(sorry if the thread title is wordy, but I couldn't think of a better way to put it) I'm making a 2D racing game in Python. The first thing, of course, is to make a car that can drive around. My question is, how could I program it so that the car would go where it is pointed when a key is pressed? I'm not exactly sure how to approach this, but I know it involves math. Thanks!

##### Share on other sites
Considering you mentioned it is a 2D game, The following answer[s] is/are assuming that you're only concerned with a coordinate system consisting of x and y [as opposed to x, y, and z].

Your answer will be dependant on how you represent the heading of the car. If you're using a vector to point what direction the car is facing, then you would normalize that vector, and multiply it by the speed you want to be moving, add it to the previous position, and make that number the current position. It would look like this :
directionLength = sqrt(direction.x * direction.x + direction.y * direction.y);position.x = position.x + (direction.x / directionLength) * speed;position.y = position.y + (direction.y / directionLength) * speed;

If you're using an angle to represent the heading, then you would use a similar version of that which is above, except you would derive 'direction' from the angle from a given axis [we'll use the x axis here] with sine and cosine to determine the direction. Like this :
direction.x = cos(angle);direction.y = sin(angle);position.x = position.x + direction.x * speed;position.y = position.y + direction.y * speed;

You don't have to divide the direction by it's length because cos and sin will return values such that sin(angle)^2 + cos(angle)^2 = 1.

Don't forget to convert your values for the angle into the appropriate form previous to calling sin() and cos(). Typically they use radians, and if you're using degrees, you have multiply them by PI/180.0

##### Share on other sites
Thanks, I'll try that.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627657
• Total Posts
2978466

• 10
• 12
• 22
• 13
• 33