feat: add collisions
This commit is contained in:
		
							
								
								
									
										32
									
								
								src/car.py
									
									
									
									
									
								
							
							
						
						
									
										32
									
								
								src/car.py
									
									
									
									
									
								
							| @@ -3,6 +3,7 @@ from math import radians | ||||
| import pygame | ||||
|  | ||||
| from src.camera import Camera | ||||
| from src.utils import segments_intersect | ||||
| from src.vec import Vec | ||||
|  | ||||
|  | ||||
| @@ -13,6 +14,7 @@ class Car: | ||||
|     COLOR = (230, 150, 80) | ||||
|     WIDTH = 0.4 | ||||
|     LENGTH = 0.6 | ||||
|     COLLISION_MARGIN = 0.4 | ||||
|  | ||||
|     def __init__(self, pos: Vec, direction: Vec) -> None: | ||||
|         self.pos: Vec = pos | ||||
| @@ -22,6 +24,7 @@ class Car: | ||||
|         self.backward: bool = False | ||||
|         self.left: bool = False | ||||
|         self.right: bool = False | ||||
|         self.colliding: bool = False | ||||
|  | ||||
|     def update(self): | ||||
|         if self.forward: | ||||
| @@ -45,6 +48,8 @@ class Car: | ||||
|             self.direction = self.direction.rotate(rotate_angle) | ||||
|  | ||||
|         self.speed *= 0.98 | ||||
|         if abs(self.speed) < 1e-8: | ||||
|             self.speed = 0 | ||||
|  | ||||
|         self.pos += self.direction * self.speed | ||||
|  | ||||
| @@ -62,3 +67,30 @@ class Car: | ||||
|         p3: Vec = pt - u - v | ||||
|         p4: Vec = pt + u - v | ||||
|         return [p1, p2, p3, p4] | ||||
|  | ||||
|     def check_collisions(self, polygons: list[list[Vec]]): | ||||
|         self.colliding = False | ||||
|         corners: list[Vec] = self.get_corners() | ||||
|         sides: list[tuple[Vec, Vec]] = [ | ||||
|             (corners[i], corners[(i + 1) % 4]) for i in range(4) | ||||
|         ] | ||||
|  | ||||
|         for polygon in polygons: | ||||
|             n_pts: int = len(polygon) | ||||
|             for i in range(n_pts): | ||||
|                 pt1: Vec = polygon[i] | ||||
|                 pt2: Vec = polygon[(i + 1) % n_pts] | ||||
|                 d: Vec = pt2 - pt1 | ||||
|  | ||||
|                 for s1, s2 in sides: | ||||
|                     if segments_intersect(s1, s2, pt1, pt2): | ||||
|                         self.colliding = True | ||||
|                         self.direction = d.normalized | ||||
|                         n: Vec = self.direction.perp | ||||
|                         dist: float = (self.pos - pt1).dot(n) | ||||
|                         if dist < 0: | ||||
|                             n *= -1 | ||||
|                             dist = -dist | ||||
|                         self.speed = 0 | ||||
|                         self.pos = self.pos + n * (self.COLLISION_MARGIN - dist) | ||||
|                         return | ||||
|   | ||||
		Reference in New Issue
	
	Block a user