Как сделать, чтоб автомобиль езжал в ту сторону, куда он направлен?

Рейтинг: 0Ответов: 1Опубликовано: 14.05.2023

У меня есть код с возможностью движения автомобиля и хотелось бы чтоб тачка езжала в ту сторону, куда она направлена.

import pygame
import sys

pygame.init()

width, height = 800, 600
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()

image = pygame.image.load('car_128.png')
image_rect = image.get_rect(center=(width // 2, height // 2))

rotation_angle = 0
rotation_speed = 2

while True:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()

keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
    rotation_angle += rotation_speed
if keys[pygame.K_w]:
    image_rect.y += 10
if keys[pygame.K_s]:
    image_rect.y -= 10
if keys[pygame.K_d]:
    image_rect.x += 10
if keys[pygame.K_a]:
    image_rect.x -= 10

rotated_image = pygame.transform.rotate(image, rotation_angle)
rotated_rect = rotated_image.get_rect(center=image_rect.center)

screen.fill((0, 0, 0))
screen.blit(rotated_image, rotated_rect)

pygame.display.flip()
clock.tick(60)

Ответы

▲ 0Принят

Вы можете использовать простые формулы синуса и косинуса:

from math import sin, cos, radians

import pygame
import sys

pygame.init()

width, height = 800, 600
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()

image = pygame.image.load('car_128.png')
image_rect = image.get_rect(center=(width // 2, height // 2))

rotation_angle = 0
rotation_speed = 2

while True:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_SPACE]:
        rotation_angle += rotation_speed
    if keys[pygame.K_w]:
        image_rect.x -= 10 * sin(radians(rotation_angle))
        image_rect.y -= 10 * cos(radians(rotation_angle))
    if keys[pygame.K_s]:
        image_rect.x += 10 * sin(radians(rotation_angle))
        image_rect.y += 10 * cos(radians(rotation_angle))
    if keys[pygame.K_d]:
        image_rect.x += 10 * cos(radians(rotation_angle))
        image_rect.y -= 10 * sin(radians(rotation_angle))
    if keys[pygame.K_a]:
        image_rect.x -= 10 * cos(radians(rotation_angle))
        image_rect.y += 10 * sin(radians(rotation_angle))

    rotated_image = pygame.transform.rotate(image, rotation_angle)
    rotated_rect = rotated_image.get_rect(center=image_rect.center)

    screen.fill((0, 0, 0))
    screen.blit(rotated_image, rotated_rect)

    pygame.display.flip()
    clock.tick(60)