0

I would like my car to be able to move around the canvas, meaning when it rotates and I press the up arrow key, it moves towards the direction that the car is facing and vice versa for the down arrow key for reversing. I have absolutely no idea where to start for this so please can someone help me.

This is the code I have so far:


import pygame, sys

def rotate(surface,angle):
    rotated_surface = pygame.transform.rotozoom(surface,-angle,1)
    rotated_rect = rotated_surface.get_rect(center = (400,300))
    return rotated_surface,rotated_rect

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A racing game')
lime = (0,255,0)

clock = pygame.time.Clock()
car = pygame.image.load('car3.png')
car_rect = car.get_rect(center= (400,300))


def game_loop():
       
    x = (display_width * 0.45)
    y = (display_height * 0.8)
    y_change = 0
    angle_change = 0
    car_speed = 5
    a = 0
    car_width = 75
    car_height = 37
    angle = 0
    crashed = False

    while not crashed:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
               crashed = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    angle_change = -5
                elif event.key == pygame.K_RIGHT:
                    angle_change = 5
                elif event.key == pygame.K_UP:
                    y_change = 5
                elif event.key == pygame.K_DOWN:
                    y_change = -5
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    y_change = 0
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    angle_change = 0
                    

        y += y_change
        angle += angle_change
        gameDisplay.fill(lime)
        car_rotated,car_rotated_rect = rotate(car,angle)
        gameDisplay.blit(car_rotated, car_rotated_rect)
        pygame.display.update()
        clock.tick(60)

game_loop()

This code displays a car on a green background, and you can rotate with the left and right arrow keys. The up and down arrow keys do not do anything.

Thank you

Rabbid76
  • 177,135
  • 25
  • 101
  • 146

0 Answers0