0

I'm trying to make a top-down car racing game where you have to press the Up key to move forward and the left and right keys to change the angle of the car. I know there are some maths behind this but I definitely don't know them. How can I make this in pygame?

  • Does this answer your question? [Moving a Sprite in the direction of an angle in Pygame](https://stackoverflow.com/questions/48832717/moving-a-sprite-in-the-direction-of-an-angle-in-pygame) – mousetail Jan 12 '21 at 14:19
  • @mousetail Using pygame.math.Vector2 is simpler I think. – BlueStaggo Jan 12 '21 at 14:20
  • I can use vectors but I want to animate the process by rotating the object and moving it in that direction. – Noob Coding Jan 12 '21 at 14:22

2 Answers2

2

You could use Vector2 from pygame.math. In your car class, you have to add two properties:

  • velocity = pygame.math.Vector2(0, speed) how fast your car moves
  • direction = 0 the direction of your car

Program your game so that on pressing the left key, direction -= dirspeed and vice versa for right. On updating you can do self.current_velocity = velocity.rotate(direction). Vector2s work just like tuples, which mean you can do something like:

x = velocity.x
y = velocity.y

There might be more maths behind it but I hope this helps.

BlueStaggo
  • 171
  • 1
  • 12
0

I think what you mean is to determine the velocity that the player moves in.

To calculate the velocity you can use sinus and cosinus from the math library:

X Velocity = Speed of the player * math.cos(Angle that you want to move to)
Y Velocity = Speed of the player * math.sin(Angle that you want to move to)

For more information I would go to https://courses.lumenlearning.com/boundless-physics/chapter/projectile-motion/ or search how velocity prediction physics work.

JakeyJJ
  • 23
  • 4