refactor: move car rendering to Car

This commit is contained in:
2025-10-18 21:01:52 +02:00
parent 2b20582b87
commit 45ed1c85c8
2 changed files with 23 additions and 13 deletions

View File

@@ -1,4 +1,8 @@
from math import radians
import pygame
from src.camera import Camera
from src.vec import Vec
@@ -6,6 +10,9 @@ class Car:
MAX_SPEED = 0.05
MAX_BACK_SPEED = -0.025
ROTATE_SPEED = radians(1)
COLOR = (230, 150, 80)
WIDTH = 0.4
LENGTH = 0.6
def __init__(self, pos: Vec, direction: Vec) -> None:
self.pos: Vec = pos
@@ -40,3 +47,18 @@ class Car:
self.speed *= 0.98
self.pos += self.direction * self.speed
def render(self, surf: pygame.Surface, camera: Camera):
pts: list[Vec] = self.get_corners()
pts = [camera.world2screen(p) for p in pts]
pygame.draw.polygon(surf, self.COLOR, pts)
def get_corners(self) -> list[Vec]:
u: Vec = self.direction * self.LENGTH / 2
v: Vec = self.direction.perp * self.WIDTH / 2
pt: Vec = self.pos
p1: Vec = pt + u + v
p2: Vec = pt - u + v
p3: Vec = pt - u - v
p4: Vec = pt + u - v
return [p1, p2, p3, p4]

View File

@@ -60,24 +60,12 @@ class Game:
def render(self):
self.win.fill(self.BACKGROUND_COLOR)
self.track.render(self.win, self.camera)
self.render_car()
self.car.render(self.win, self.camera)
if self.show_fps:
self.render_fps()
pygame.display.flip()
def render_car(self):
u: Vec = self.car.direction * 0.3
v: Vec = self.car.direction.perp * 0.2
pt: Vec = self.car.pos
p1: Vec = pt + u + v
p2: Vec = pt - u + v
p3: Vec = pt - u - v
p4: Vec = pt + u - v
pts: list[Vec] = [p1, p2, p3, p4]
pts = [self.camera.world2screen(p) for p in pts]
pygame.draw.polygon(self.win, (230, 150, 80), pts)
def on_key_down(self, event: pygame.event.Event):
if event.key == pygame.K_w:
self.car.forward = True