Public Group

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

This topic is 4160 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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.

1. 1
Rutin
47
2. 2
3. 3
4. 4
5. 5

• 13
• 10
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632992
• Total Posts
3009756
• ### Who's Online (See full list)

There are no registered users currently online

×