Jump to content
  • Advertisement
Sign in to follow this  
bugscripts

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!