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:
+13
-6
@@ -1,8 +1,10 @@
|
||||
from .unit import Unit
|
||||
from .bomb import Explosion
|
||||
from engine.collision_system import CollisionLayer
|
||||
|
||||
class Mine(Unit):
|
||||
def __init__(self, game, position=(0,0), id=None):
|
||||
super().__init__(game, position, id)
|
||||
super().__init__(game, position, id, collision_layer=CollisionLayer.MINE)
|
||||
self.speed = 1.0 # Mine doesn't move but needs speed for consistency
|
||||
self.armed = True # Mine is active and ready to explode
|
||||
|
||||
@@ -11,13 +13,18 @@ class Mine(Unit):
|
||||
pass
|
||||
|
||||
def collisions(self):
|
||||
"""Check if a rat steps on the mine (has position_before on mine's position)."""
|
||||
"""Check if a rat steps on the mine using optimized collision system."""
|
||||
if not self.armed:
|
||||
return
|
||||
|
||||
# Check for rats that have position_before on this mine's position
|
||||
for rat_unit in self.game.unit_positions_before.get(self.position, []):
|
||||
if hasattr(rat_unit, 'sex'): # Check if it's a rat (rats have sex attribute)
|
||||
|
||||
# Use collision system to check for rats at mine's position_before
|
||||
victim_ids = self.game.collision_system.get_units_in_cell(
|
||||
self.position, use_before=True
|
||||
)
|
||||
|
||||
for victim_id in victim_ids:
|
||||
rat_unit = self.game.get_unit_by_id(victim_id)
|
||||
if rat_unit and hasattr(rat_unit, 'sex'): # Check if it's a rat
|
||||
# Mine explodes and kills the rat
|
||||
self.explode(rat_unit)
|
||||
break
|
||||
|
||||
Reference in New Issue
Block a user