How do I use .spritecollide() in pygame to detect for collisions?

I am trying to learn how to use pygame by creating a simple ‘shmup’ game with blocks. When running the code, no errors are shown, however the game does not seem to be detecting collisions between the sprites. Am I using this incorrectly?
Any help much appreciated. If it would be easier to run the code for yourself that should be possible as there are no external files used.

    hits = pygame.sprite.spritecollide(player,mobs, False) 
    if hits:
        running = False

All code:

import pygame
import random
import time


width = 480
height = 600

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

#initialise pygame and create window
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption("Shoot 'Em Up!")
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    def __init__(self):  #this is mandatory, it loads the built in sprite 
        self.image = pygame.Surface((50,40))

        self.rect = self.image.get_rect()
        self.rect.centerx = width / 2
        self.rect.bottom = height - 10
        self.speedx = 0

    def update(self):
        self.speedx = 0    #thi section makes the sprite move, sets x speed
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx = -5
        if keystate[pygame.K_RIGHT]:
            self.speedx = 5

        self.rect.x += self.speedx
        # sets the boundaries of screen
        if self.rect.right > width:
            self.rect.right = width
        if self.rect.left < 0:
            self.rect.left = 0

class Mob(pygame.sprite.Sprite):
    def __init__(self):
        self.image = pygame.Surface((30,40))
        self.rect = self.image.get_rect()

        self.rect.x = random.randrange(0, width - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(1, 8)
        #randomising angle of movement
        self.speedx = random.randrange(-3, 3)

    def update(self):
        self.rect.x += self.speedx
        self.rect.y += self.speedy
        if > height + 10 or self.rect.left < -30 or 
self.rect.right > width + 30:
            self.rect.x = random.randrange(0, width - self.rect.width)
            self.rect.y = random.randrange(-100, -40)
            self.speedy = random.randrange(3, 8)

all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()  #make a spearte group for mobs to enable 
collisions between groups
player = Player()

# spawning the mobs
for i in range (8):  #start with spawning 8
    m = Mob()

#Game Loop
running = True

while running:
    clock.tick(60) #keep running at the right speed

    for event in pygame.event.get():  #process events (inputs)
        if event.type == pygame.QUIT:  #check for closing of window
            running = False


    # check to see if a mob hit a player
    hits = pygame.sprite.spritecollide(player,mobs, False) # which sprites 
do you want to check for collisisons
    if hits:
        running = False

    all_sprites.draw(screen) #where to draw sprites in the group


All topic

Violation of energy conservation during collisions of a particle with different sections of a rod

Imagine a homogenous rod with total mass $M$ and length $l$ floating in free space without any force or constraint acting on it. Then, think about two possible scenarios. In the first, a particle with lineal momentum $mv$ impacts right at the center of the rod. In the second, the same particle with same lineal momentum impacts right at one of the ends of the rod.

First case

In the first case there will be no rotation, only translation. We apply conservation of momentum (where I think there are two cases, one with the particle having final lineal momentum $v_f$ and the other with $-v_f$, but i will omit the first one).

$$mv = MV – mv_f quad quad V= frac{m}{M}(v+v_f)$$

Then the final energy is:

$$E_f = frac{1}{2} MV^2 + frac{1}{2} mv_f^2 = frac{m^2}{2M} (v+v_f)^2 + frac{1}{2} mv_f^2$$

Second case

In the second case there will only be rotation (or so I think, but I’m getting really confused so that’s why I’ve come up with this scenarios to try to prove it) without translation. Again we apply conservation of momentum:

$$mv = MV – mv_f quad quad V= frac{m}{M}(v+v_f)$$

Let me explain what $V$ represents in this case. Since the rod rotates all the points in it don’t have the same velocity, but, since the velocity increases linearly with the radius and the rod is homogenous, if the velocity of the ends is $2V$ (which I compell it to be this way) then the average speed of thte whole rod is $V$. Then we proceed (the cross product of $L$ doesn’t matter):

$$I omega = L = pr = MV l/4 = frac{ml(v+v_f)}{4}$$

So the final energy of the whole system is (having $I=frac{1}{12}Ml^2$):

$$E_f= frac{1}{2} frac{(Iomega)^2}{I} + frac{1}{2} mv_f^2 = frac{3m^2}{8M} (v+v_f)^2 + frac{1}{2} mv_f^2$$

So comparing the two cases, there’s a difference in the final energy, specifically a difference of $frac{m^2}{8M} (v+v_f)^2$, which doesn’t make sense.


This difference can mean various things, and I don’t know which of this ones is, or even if it implies something else I haven’t thought about. But before, there’s something I don’t understand and then there would be no need of other explanations.

As I’ve said the average velocity of the rod is $V$ so why should it have different speed when rotating than if the whole rod is advancing? In the end, the product mass times velocity is the same. So that’s one thing I don’t understand.

If that’s not the case and the kinetic energy is different for some reason here’s the explanations I’ve thought about for this difference in the energies:

  1. In the second case there’s also kinetic energy in the form of translation of the rod, and not only rotation, specifically with a translational kinetic energy of $frac{m^2}{8M} (v+v_f)^2$, but why this specific quantity?
  2. Actually, apart from the rotation, the rod has the same translational kinetic energy as in the first case, and $v_f$ in the second case is what causes the difference, being much smaller, so in this case the rod would have much more kinetic energy in the end when having the particle impact at one of the ends than having it impact at the very center.
  3. There’s no translation, which would agree with my hypothesis, and $v_f$ would be bigger in the second case than in the first.

All topic

birthday problem – which solution for expected value of collisions is correct?

I am trying to understand the difference of the two solutions for the expected value of collisions for the birthday problem:

  1. derives the following solution:

… so the expected number of people who share birthdays with somebody is $nleft(1-(1-1/N)^{n-1}right)$.


  1. gives

This leads to an expectation value $lambda$ (date collisions in terms of the lambda distribution) of $lambda = frac{n(n-1)}{2m}$

For $2^{32}$ “days” and $10^6$ people,

  1. results in $E_1 = 232.8033$


  1. results in $E_2 = 116.4152$

It looks like that $frac{E_1}{E_2} approx 2$.

As $E_2$ gives the number of collision pairs instead of number of people involved in collisions, this seems reasonable to me.

Which of the solutions is correct? Is $E_2$ just an approximation?

All topic

How does resolve head-on collisions?

In, whenever I run into another snake head on, I seem to lose the exchange and die while my opponent lives on. It’s most apparent when there is a fresh kill and we’re both racing (boosting) from opposite ends of the former snake until we inevitably meet in the middle.

I’m sure this is just a bit of confirmation bias, but when two snakes run into each other head on, how does the game determine which one survives and which one becomes snake food?

For anyone not familiar with this online game: is a large-field, multi-player game where you move your “snake” around trying to avoid running into others while causing others to run into you.

All topic

Is it possible to tile box colliders without causing “false” collisions in Unity3D?

This is in regards to something like a sidescroller where you have a tiled map where each tile uses a 2d box collider.

If you use a 2d circular collider as an example for your character, as it rolls across a series of tiled 2d box colliders, it will occasionally collide with the seams between tiles rather than rolling smoothly across them.

In my scenario here, the tiles are 1×1 units snapped directly adjacent to each other. When rolling a 2d circular collider across a row of tiles, it goes mostly smooth but the more force applied, the greater chance of the circle flying up into the air rather than it’s y staying the same as it rolls across them.

The obvious conclusion I had was to use edge colliders instead which works fine, but I’m hoping to find a way to completely eliminate this problem even with just 2d box colliders.


All topic

Farseer Physics: Enabling collisions between jointed bodies

When I connect two bodies (a dynamic ball and a static plank) with a rope joint, they ignore collisions between each other, but both will collide with other bodies/fixtures. I’d like to be able to make them collide without having to make a child-parent system for each body.
Can’t find much online.

For what it’s worth I’ve tried:

body1.CollidesWith = Category.All;
body2.CollidesWith = Category.All;  

Didn’t work.

Thanks in advance.

All topic

What’s the best way to deal with platformer tile collisions?

I am starting with game development and creating a basic platformer game. I already have searched a lot and found some ways to implement the platformer aspect to the game, like apply a gravity, velocity and so on.

Everything is good, but always when I implement a way to deal with the collisions, a bug appears. If I fix it, it appears at other side, etc. The main problem is when the player intersects a tile and I need push him up back. The most simple way that I found is this:

player.Y = tile.Y - player.height;

The most problems comes when you also need verify the X axis, the player is pushed out from the tile, or it is thrown at other tile position, like this issue I had when trying to implement the XNA Platformer Example. Or even pass through the tiles if you are going too fast.

After some research I found a good way to avoid all this problems: instead of move the player to the next position and deal with the tiles to push him back, calculate a safe distance and move the player following this. The “safe distance” is for example, the player.Y += player.Velocity.Y, but if any tile is at the way, the safe distance is decreased to the player don’t enter in the tile.

I read this excelent article and it’s what is said about the algoritm:

  1. The total movement of the player along that direction is then the minimum between the distance to closest obstacle, and the amount that you wanted to move in the first place.
  2. Move player to the new position. With this new position, step the other coordinate, if still not done.

So, the best way is use the “safe distance” method?

All topic

What would be the effects of warp collisions?

Triggered by a recent question I was wondering what actually would happen to a ship (e.g. the Enterprise-D NCC-1701) that collides with a stationary object such as a) another ship of a similar configuration or b) a gigantic structure like a moon or even a planet.

We know the deflector is supposed to keep interstellar dust (not to be confused with ordinary dust, which is a different thing) from ripping large holes in the ship.

At first, one thinks “Obvious. Everyhing explodes.” But does it really? Would the deflector manage to actually deflect both masses? If not, where is the threshold of what a deflector can handle? Would the ship maybe tunnel right through the object, because of wibbly-wobbly space wobblification by the warp field? It does do some weird things to the space right in front and behind the vessel.

Important remark: We cannot approach this with what we know about physics at all. For all intents and purposes, both ships must measure the other ship travelling faster than light, resulting in it having infinite (or rather undefined) mass and by extension momentum. If we start with that reasoning any ship jumping to warp would suck in the entire universe (it takes a moment, but think about it). So, obviously we cannot apply our intuition (even our relativistic intuition) here.

All topic

How can I get visually accurate collision normals with sphere collisions?

enter image description here

I’m solving simple 3D sphere collisions by checking the sphere for overlap with a mesh, finding the nearest point on that mesh’s surface to the center of the sphere, and then resolving the collision by moving the sphere out of the mesh using the normal and the penetration distance.

To find the normal, I’m using the normalized vector from the nearest point on the mesh to the center of the sphere.

Now I’m trying to resolve a collision where the sphere has overlapped more than one collider. How I’m currently solving it is by iterating through all the meshes and checking to see if the last correction solved the collision.

In the scenario shown in the bottom image, this can cause a problem when trying to determine a collision normal. The two collisions return two different normals, as they should (Though, Depending on which collision was resolved first, the correction from the right box would solve the collision with the left box, in which case there would only be one normal).

Now, mathematically, that all makes sense, but visually causes a problem. If I’m trying to determine a single normal to, say, bounce the ball off the surface create by those two meshes, any normal that takes both collision normals into effect would be inaccurate. Visually, one would expect the collision normal to be straight op, but since one of the collision normals is at an angle, I would need to somehow determine that that is a sort of “false” normal.

The solution that comes to mind is to order the collision checks by their distance from the sphere, thereby ensuring that, in that scenario, the angled normal never even comes into play. Is this an accurate way to do this, or would that cause other problems I’m not seeing?

All topic

Shaping Bezier objects and applying Physics collisions?

Logo animation project
First part is dropping chromed tubes on a floor, let them bounce and roll a bit. The rolling stops at frame 90.

Second part is for the lighting to go dark, and the tubes emit a neon glow.
Tubes then animate shape into an outline of a frog.

Chrome tubes prior to animation
The problem is that I am using Mesh Objects for the falling tubes, but cannot shape them like a Bezier Line.

Alternatively, I can shape Bezier Tubes for part 2 as I wish, but cannot apply a Collision physics to them so that they bounce and roll on the floor in part 1.

My current solution is to create part 1 until frame 90 using Mesh Tubes. For part 2 I create duplicate Bezier Tubes in the same precise orientation as the Mesh Tubes at frame 90. I then animate the Bezier Tubes to change their shapes from frame 90 to the end. Any suggestions for a better solution are welcome. Placing the Bezier Tubes is quite tedious.

A partial solution is to use >both<. First the mesh object for the bounce and roll. I put these on a layer. Second the bezier objects for the shape animations. I put these on a second layer after alignment with the mesh tubes on layer one.

All topic