Skip to content Skip to sidebar Skip to footer

Pygame Collision Code

First of all, I have to say that I'm french (so that you understand why I make all these mistakes lol) I'm working on a physic game with python, pygame and pymunk : A ball (I'll ca

Solution 1:

Since you are already using pymunk why not use it to detect the collision (instad of pygame as in the other answer).

Basically you need to create and add a pymunk.Shape object defining your goal, set its collision type and add a collision handler between the object and your player ball X.

Something like this should do it (pymunk 5.0 and later):

# Add a new collision type
COLLTYPE_GOAL = 3# Define collision callback function, will be called when X touches Y defgoal_reached(space, arbiter):
    print"you reached the goal!"returnTrue# Setup the collision callback function
h = space.add_collision_handler(COLLTYPE_BALL, COLLTYPE_GOAL)
h.begin = goal_reached

# Create and add the "goal" 
goal_body = pymunk.Body()
goal_body.position = 100,100
goal = pymunk.Circle(goal_body, 50)
goal.collision_type = COLLTYPE_GOAL
space.add(goal)

In older versions a handler is set in this way instead:

# Setup the collision callback function
space.add_collision_handler(COLLTYPE_BALL, COLLTYPE_GOAL, goal_reached, None, None, None)   

Solution 2:

As I understand it, what you need is to know if sprites are colliding, and then if they are you want to do something. Pygame has a spritecollide function. Here is a wrapper function that makes it a bit easier, it will return True if two sprites are colliding.

defcollides(sprite1,sprite2):
    sprite1_group = pygame.sprite.RenderUpdates()    #this creates a render updates group, as the sprite collide function requires one of its arguments to be a group.
    sprite1_group.add(sprite1)
    collisions = pygame.sprite.spritecollide(sprite2, sprite1_group, False)  #runs spritecollide, specifying the sprite, the group, and the last parameter, which should almost always be false.for other in collisions:
        if other != sprite2:     #spritecollide registers a sprites collision with itself, so this filters itreturnTrue

now you have a function that can detect collisions, like so:

if collides(sprite1,sprite2)

If you need to handle this event without disrupting your regular code, you can always use threading.

Post a Comment for "Pygame Collision Code"