Friday, August 30, 2013

Finally! She bumps into walls (sorta)!



Would you like to know how I did it?

Ok.

So, in the level class that is being used to hold the level sprites I use the collision detection algorithms that come with Pygame.

level_bumps = spritecollide(sprite,self.walls,False)
 
Now, it isn't quite as simply as it sounds, mostly because all it does is give a list of all the sprites of a given group that intercept with a given sprite (that last argument is whether or not I want to destroy the sprites afterwards... which is no).  While this does make things easier on me (meaning that I don't have to program checking for when one pixel loves another pixel), I still have to program what should be done when two sprites collide.  After all, any sauvy reader should be able to point out that the floor is made up of sprites.

At the moment, the functionality is for walls that are not corners, as the video points out.  Still, there was an interesting way that I achieved this.  Though the power of objects!

So, first, we capture those sprites that meet another sprite:


def checkCollision (self,sprite):  level_bumps = spritecollide(sprite,self.walls,False)  for items in level_bumps:     items.onCollision(sprite) 

Notice that weird function?  Yeah, that doesn't come with Pygame.  I added those using a class that is a subclass of Sprite that I made that simply has that function.  Whether it does anything depends on whether or not I bothered to fill anything in to the overloaded class that would be, say, a wall.

Here is what it looks like for a wall by the way:

def onCollision (self,sprite):
        offset = 5
        if self.orientation == NORTH:
            relocate = self.rect.bottom+offset
            sprite.rect.top = relocate
        elif self.orientation == SOUTH:
            relocate = self.rect.top-offset
            sprite.rect.bottom = relocate
        elif self.orientation == EAST:
            relocate = self.rect.right+offset
            sprite.rect.left = relocate
        elif self.orientation == WEST:
            relocate = self.rect.left-offset
            sprite.rect.right = relocate


The result?  Well, you can see the video, can you?

No comments:

Post a Comment