I drive a car using the key buttons. It works too. I would like in addition, when the car is at a standstill, turn the wheels without the car turning. If I then drive forwards / backwards, the car should start moving in the direction of the turned wheels. Like in real life. But in my code, the car is moving when i move the wheels.There is something wrong with the if Condition?
import pygame
import sys
import math
pygame.init()
cell_size = 40
cell_number = 20
breite = int(cell_size * cell_number )
hoehe = int( cell_size * cell_number )
screen = pygame.display.set_mode((breite,hoehe))
clock = pygame.time.Clock()
class MyCar(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(auto_img,(30,66))#.convert_alpha()
self.rect = self.image.get_rect()
self.rect.center = (x,y)
self.rect.x = x
self.rect.y = y
self.driving_angle = 0
self.speed = 5
self.links = False
self.rechts = False
self.vor = False
self.zurueck = False
self.steering_angle = 0
def update(self):
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.links = True
elif event.key == pygame.K_RIGHT:
self.rechts = True
elif event.key == pygame.K_UP:
self.vor = True
elif event.key == pygame.K_DOWN:
self.zurueck = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
self.links = False
elif event.key == pygame.K_RIGHT:
self.rechts = False
elif event.key == pygame.K_UP:
self.vor = False
elif event.key == pygame.K_DOWN:
self.zurueck = False
if self.vor or self.zurueck:
dx = math.cos(math.radians(self.driving_angle))
dy = math.sin(math.radians(self.driving_angle))
if self.vor:
self.rect.y -= int(self.speed * dx)
self.rect.x -= int(self.speed * dy)
elif self.zurueck:
self.rect.y += int(self.speed * dx)
self.rect.x += int(self.speed * dy)
if self.links:
self.steering_angle -=1
self.steering_angle=min(self.steering_angle,120)
elif self.rechts:
self.steering_angle +=-1
self.steering_angle=max(self.steering_angle,-120)
if self.rechts:
self.driving_angle += self.steering_angle
while self.driving_angle < 0:
self.driving_angle += 360
elif self.links:
self.driving_angle -= self.steering_angle
while self.driving_angle > 359:
self.driving_angle -= 360
def blitRotateCenter(image, left, top, angle):
rotated_image = pygame.transform.rotate(image, angle)
new_rect = rotated_image.get_rect(center = image.get_rect(center = (left, top)).center)
screen.blit(rotated_image, new_rect)
return new_rect
auto_img = pygame.image.load("Bilder/car.png").convert_alpha()
auto = MyCar(breite/2,hoehe-100)
auto_sprite = pygame.sprite.Group()
auto_sprite.add(auto)
while True:
clock.tick(10)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
auto.update()
new_auto_rect = blitRotateCenter(auto.image, *auto.rect.center, auto.driving_angle)
auto.rect=new_auto_rect
pygame.display.flip()