changeset 155:b2e0f1246c38

Hook up bitmasked based collisions (mask caching may be unnecessary, please comment on whether this effects performance for you).
author Simon Cross <hodgestar@gmail.com>
date Tue, 05 Apr 2011 22:51:14 +0200
parents 1008a7bae425
children 0b0dbfb50e5f
files skaapsteker/physics.py
diffstat 1 files changed, 14 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/skaapsteker/physics.py	Tue Apr 05 22:43:09 2011 +0200
+++ b/skaapsteker/physics.py	Tue Apr 05 22:51:14 2011 +0200
@@ -8,6 +8,7 @@
 import pygame
 import pygame.draw
 import pygame.sprite
+from pygame.mask import from_surface
 
 from . import options
 from .constants import EPSILON
@@ -35,7 +36,7 @@
     debug_color = (240, 0, 0)
 
     floor = False  # We special case collisions with ground objects
-    block = False 
+    block = False
 
     def __init__(self, *args, **kwargs):
         super(Sprite, self).__init__(*args, **kwargs)
@@ -45,6 +46,7 @@
         self.collide_rect = pygame.Rect(0, 0, 10, 10) # rectangle we use for collisions
         self.image = pygame.Surface((10, 10))
         self.image.fill((0, 0, 200))
+        self._mask_cache = {} # image id -> collision bit mask
 
     def init_pos(self):
         self._float_pos = self.rect.topleft
@@ -81,8 +83,18 @@
         delta_pos = self.rect.left - old_pos[0], self.rect.top - old_pos[1]
         self.collide_rect.move_ip(delta_pos)
 
+    def _check_mask(self):
+        image_id = id(self.image)
+        mask = self._mask_cache.get(image_id, None)
+        if mask is None:
+            mask = self._mask_cache[image_id] = from_surface(self.image)
+        self.mask = mask
+
     def check_collides(self, other):
-        return True # default to relying purefly on collision_layer and collides_with
+        # check bitmasks for collision
+        self._check_mask()
+        other._check_mask()
+        return pygame.sprite.collide_mask(self, other)
 
     def collided(self, other):
         pass