Pygame - create a sprite in the direction in which it is

I am doing a top-down racing game, and I want to make the car spin when you press the left and right keys (Ive already done this part), the sprite rotation is stored in a variable as degrees. I would like him to move in accordance with the acceleration in the direction in which he is. I can figure out part of the acceleration myself by simply figuring out which pixel is in that direction. Can someone give me some simple code to help with this?

Here is the content of the corresponding class:

def __init__(self, groups):
    super(Car, self).__init__(groups)
    self.originalImage = pygame.image.load(os.path.join("Data", "Images", "Car.png")) #TODO Make dynamic
    self.originalImage.set_colorkey((0,255,0))
    self.image = self.originalImage.copy() # The variable that is changed whenever the car is rotated.

    self.originalRect = self.originalImage.get_rect() # This rect is ONLY for width and height, the x and y NEVER change from 0!
    self.rect = self.originalRect.copy() # This is the rect used to represent the actual rect of the image, it is used for the x and y of the image that is blitted.

    self.velocity = 0 # Current velocity in pixels per second
    self.acceleration = 1 # Pixels per second (Also applies as so called deceleration AKA friction)
    self.topSpeed = 30 # Max speed in pixels per second
    self.rotation = 0 # In degrees
    self.turnRate = 5 # In degrees per second

    self.moving = 0 # If 1: moving forward, if 0: stopping, if -1: moving backward


    self.centerRect = None

def update(self, lastFrame):
    if self.rotation >= 360: self.rotation = 0
    elif self.rotation < 0: self.rotation += 360

    if self.rotation > 0:
        self.image = pygame.transform.rotate(self.originalImage.copy(), self.rotation)
        self.rect.size = self.image.get_rect().size
        self.center() # Attempt to center on the last used rect

    if self.moving == 1:
        self.velocity += self.acceleration #TODO make time based

    if self.velocity > self.topSpeed: self.velocity = self.topSpeed # Cap the velocity
+3
source share
2 answers

Trigonometry: Formula to get your coordinate:

# cos and sin require radians
x = cos(radians) * offset
y = sin(radians) * offset

. ( , ).

:

def rad_to_offset(radians, offset): # insert better func name.
    x = cos(radians) * offset
    y = sin(radians) * offset
    return [x, y]

loop_update - - :

# vel += accel
# pos += rad_to_offset( self.rotation, vel )

math.cos, math.sin: ,

. /etc , .

# store radians, but define as degrees
car.rotation_accel = radians(45)
car.rotation_max_accel = radians(90)
+4

, (*). , , .


(*) :-), .

+1

All Articles