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

Started by
1 comment, last by bugscripts 16 years, 10 months ago
(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!
Advertisement
Considering you mentioned it is a 2D game, The following answer is/are assuming that you're &#111;nly concerned with a coordinate system consisting of x and y [as opposed to x, y, and z].<br><br>Your answer will be dependant &#111;n 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 :<br><pre>directionLength = sqrt(direction.x * direction.x + direction.y * direction.y);<br>position.x = position.x + (direction.x / directionLength) * speed;<br>position.y = position.y + (direction.y / directionLength) * speed;</pre><br><br>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 :<br><pre>direction.x = cos(angle);<br>direction.y = sin(angle);<br>position.x = position.x + direction.x * speed;<br>position.y = position.y + direction.y * speed;</pre><br>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.<br><br>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
Thanks, I'll try that.

This topic is closed to new replies.

Advertisement