Implement optimized collision detection system using NumPy
- Introduced a hybrid collision detection approach that utilizes NumPy for vectorized operations, improving performance for games with many entities (200+). - Added a spatial grid for efficient lookups and AABB (Axis-Aligned Bounding Box) collision detection. - Implemented a new `CollisionSystem` class with methods for registering units, checking collisions, and managing spatial data. - Created performance tests to benchmark the new collision system against the old O(n²) method, demonstrating significant speed improvements. - Updated existing code to integrate the new collision detection system and ensure compatibility with game logic.
This commit is contained in:
+25
-8
@@ -1,5 +1,6 @@
|
||||
from .unit import Unit
|
||||
from .rat import Rat
|
||||
from engine.collision_system import CollisionLayer
|
||||
import random
|
||||
|
||||
# Costanti
|
||||
@@ -7,7 +8,7 @@ AGE_THRESHOLD = 200
|
||||
|
||||
class Gas(Unit):
|
||||
def __init__(self, game, position=(0,0), id=None, parent_id=None):
|
||||
super().__init__(game, position, id)
|
||||
super().__init__(game, position, id, collision_layer=CollisionLayer.GAS)
|
||||
self.parent_id = parent_id
|
||||
# Specific attributes for gas
|
||||
self.speed = 50
|
||||
@@ -24,13 +25,29 @@ class Gas(Unit):
|
||||
self.die()
|
||||
return
|
||||
self.age += 1
|
||||
#victims = self.game.unit_positions.get(self.position, [])
|
||||
victims = [rat for rat in self.game.unit_positions.get(self.position, []) if rat.partial_move>0.5]
|
||||
for rat in self.game.unit_positions_before.get(self.position, []):
|
||||
if rat.partial_move<0.5 and rat is Rat:
|
||||
victims.append(rat)
|
||||
for victim in victims:
|
||||
victim.gassed += 1
|
||||
|
||||
# Use optimized collision system to find rats in gas cloud
|
||||
victim_ids = self.game.collision_system.get_units_in_cell(
|
||||
self.position, use_before=False
|
||||
)
|
||||
|
||||
for victim_id in victim_ids:
|
||||
victim = self.game.get_unit_by_id(victim_id)
|
||||
if victim and isinstance(victim, Rat):
|
||||
if victim.partial_move > 0.5:
|
||||
victim.gassed += 1
|
||||
|
||||
# Check position_before as well
|
||||
victim_ids_before = self.game.collision_system.get_units_in_cell(
|
||||
self.position, use_before=True
|
||||
)
|
||||
|
||||
for victim_id in victim_ids_before:
|
||||
victim = self.game.get_unit_by_id(victim_id)
|
||||
if victim and isinstance(victim, Rat):
|
||||
if victim.partial_move < 0.5:
|
||||
victim.gassed += 1
|
||||
|
||||
if self.age % self.speed:
|
||||
return
|
||||
parent = self.game.get_unit_by_id(self.parent_id)
|
||||
|
||||
Reference in New Issue
Block a user