Skip to content
Advertisement

Move Character with Vector

I am teaching myself pygame and am looking at making my character able to rotate and then move in the direction they are facing.

I can do the rotation but cannot get the character to move in the direction the image is then facing.

The code is on Trinket HERE

JavaScript
JavaScript

Advertisement

Answer

Rotate the player around its center (see How do I rotate an image around its center using PyGame?):

JavaScript

Use an attribute x and y to store the position of the player with floating point accuracy.

JavaScript

Compute the direction of the player dependent on the angle with the trgonometric function math.sin and math.cos. Change the position attributes and update the rect attribute:

JavaScript

The y-axis needs to be reversed (-dy) as the y-axis is generally pointing up, but in the PyGame coordinate system the y-axis is pointing down. In addition, a correction angle must be deducted (+ 90). Since the “angle” is 0 ° when the sprite is looking up, you need to add 90 ° to the angle for the calculation of the direction vector.

See also te in pygame while moving with the keys](How to turn the sprite in pygame while moving with the keys.


Class Bob:

JavaScript

When setting the starting position of the player, you need to set the x, y and rect attribute:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement