Как сделать коллизию в pygame
Collision detection is a very often concept and used in almost games such as ping pong games, space invaders, etc. The simple and straight forward concept is to match up the coordinates of the two objects and set a condition for the happening of collision.
In this article, we will be detecting a collision between two objects where one object would be coming in a downward direction and the other one would be moved from the left and right with key control. It’s the same as to escape from the block falling on the player and if block collides the player, then the collision is detected.
Let’s see the part wise implementation:
Part 1:
Python3
This is the basic simple code for creating a window screen and setting up the caption, icon, and some pre-defined variables which are not so important to get into in deep. The pixel variable is the size of the block image i.e 64 pixels.
Part 2:
Python3
Here we are displaying the player and the block at their respective X and Y positions. The block’s X position is random in each round.
Note: Wherever the pixel word is used, it is used to subtract 64 pixels from the given position so that the full image is shown
E.g: The block if shown is at width position, then it will be drawn starting from that point and hence it will be shown out of the screen. Hence we are subtracting 64 pixels to be viewing the image full
First, we check if the block passes through the player’s horizontal line. We will set the range such that the block’s base horizontal line should match the player’s horizontal line. In the above image, block 2 and 3 having their baseline out of range of player P’s top and bottom surface line. Hence, they are not in the collision range. Block 1’s baseline is in the range of the player P’s top and bottom. Hence we further see that the block comes in the range of the player’s vertical range or not.

Here, we check the range of player’s left and right side surface dimensions with the blocks left and right surfaces. Here, the blocks 2 and 3 when coming down, will collide the player, and hence the range of 2 and 3 block’s range are between player’s X and player’s Y position.
Hence, this concept is to used to detect the collision.
Part 3:
Python3
the crash function defines the collision condition.
In the first IF condition, we check the horizontal collision. Here, if the player’s Y position is less than blocks Y position, i.e the block is passed away from the player’s horizontal range, then the next condition is to be checked is horizontal. Pixel is added to blockYPosition because its Y position is at top of the block and the bottom or base of the block is a block’s top position + its pixel size(image size).
The second IF condition checks the vertical collision. If the block is passing from the horizontal range then only check for vertical, so that the block’s collision is detected in all its four sides. Now, if the players X position is greater than block’s X position, i.e block is at left w.r.t player. Here, if the block’s starting position is less than player starting position and block’s end position(block Y position + pixel) is greater than player starting position, this means that the block will overlap the player’s starting position and hence collide. This is shown in the above vertical collision image for block 2.
Similarly, the second range is given that if the blocks start position is less than the player’s end position and blocks end position is greater than the player’s end position. This is shown for the same image for block 3.
The image clearly explains the view of the collision.
Hence, if a collision happens, we will move the block to below the screen i.e at 1000+ distance below so that it would be invisible and the new block will not appear.
How do I detect collision in pygame?
I have made a list of bullets and a list of sprites using the classes below. How do I detect if a bullet collides with a sprite and then delete that sprite and the bullet?
![]()
![]()
5 Answers 5
In PyGame, collision detection is done using pygame.Rect objects. The Rect object offers various methods for detecting collisions between objects. Even the collision between a rectangular and circular object such as a paddle and a ball can be detected by a collision between two rectangular objects, the paddle and the bounding rectangle of the ball.
Test if a point is inside a rectangle
Test if two rectangles overlap
Furthermore, pygame.Rect.collidelist and pygame.Rect.collidelistall can be used for the collision test between a rectangle and a list of rectangles. pygame.Rect.collidedict and pygame.Rect.collidedictall can be used for the collision test between a rectangle and a dictionary of rectangles.
The collision of pygame.sprite.Sprite and pygame.sprite.Group objects, can be detected by pygame.sprite.spritecollide() , pygame.sprite.groupcollide() or pygame.sprite.spritecollideany() . When using these methods, the collision detection algorithm can be specified by the collided argument:
The collided argument is a callback function used to calculate if two sprites are colliding.
What does this all mean for your code?
pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. The position of the rectangle can be specified by a keyword argument. For example, the centre of the rectangle can be specified with the keyword argument center . These keyword arguments are applied to the attributes of the pygame.Rect before it is returned (see pygame.Rect for a list of the keyword arguments).
See *Why is my collision test always returning ‘true’ and why is the position of the rectangle of the image always wrong (0, 0)?
You do not need the x and y attributes of Sprite and Bullet at all. Use the position of the rect attribute instead:
Pygame Sprite Collision Detection
report this ad
report this ad
report this ad
This is a tutorial on the Collision detection between sprite(s) in Pygame.
One of the many advanced topics in game development in Collision detection. This refers to the collision between two Sprites (objects) in the game environment. In this pygame tutorial we’ll explain how to detect and deal with collisions.
Rect objects
In order to be able to implement collision detection, you first need to know how pygame detects collisions between sprites.
Every Sprite in pygame has (should) have a rect or “rectangle” object assigned to it. This rectangle object has the same width and height as the Sprite itself and represents it’s boundaries.
This “rectangle” around the player is obviously a hidden (not visible) one and used for scenarios like collision detection. Pygame comes with several functions that can detect if two or more rect objects are intersecting with each other, otherwise known as a “collision”.
Using the below method on a rect object, you can determine whether it is in contact with the rect object that has been passed into it’s parameters. In simpler words, you can determine whether Sprite A is in contact with Sprite B.
It returns True if the rectangles of the two objects overlap in anyway way, otherwise returns False.
Sprite Collision Functions
spritecollideany()
The colliderect() is effective, but there are better collision detection functions in Pygame. The most commonly used function is spritecollideany() which takes two parameters, a sprite and a group.
The benefit of this function is that no matter how large the group, it will detect whether or whether not the sprite is in collision with any of the sprites within the group. It will return True if a collision was detected, otherwise False. If no collision occurred, the value None will be returned.
Remember that as we explained earlier, these collisions are judged based of the intersection of the rect objects of the sprites.
groupcollide()
Another effective function is groupcollide() . Unlike spritecollideany() it occurs between two groups, which it takes as the first and second parameter.
The return value from this function is in the form of a dictionary where the colliding sprites of group1 are they keys and the value is the list of sprites in group2 that they intersect.
This function can also take third and fourth (optional) parameters called dokill1 and dokill2 , which take True or False values. If dokill1 is True, the colliding sprites from group1 will be removed using the kill method. And if dokill2 is True, sprites from group2 will be removed.
Collision Detection Example
Finally a real life example to complete the topic of Pygame Sprite collision detection. We’re taking this example from our pygame tutorial where we made a 2D car game where the goal was to dodge the incoming cars.
In such a game, we had to implement a system where we were continuously checking for the collision between the Player and the incoming cars. The below code was extracted from this car game. For the full code, refer to the tutorial.
For reference, P1 is the player sprite object. enemies is the sprite group in which the sprites of the incoming cars are stored. DISPLAYSURF is the name of the pygame display (background/screen) and all_sprites is a sprite group which contains all the sprites in the game.
The concept is simple. If the spritecollideany() returns True, the if statement will execute. Since the objective is to make a game over screen, the screen will turn red and the display will update to reflect this change. Next all the sprites will be killed using the kill method and after two seconds the game and program will be closed respectively.
You can find another example of collision detection in our Pygame platformer series. The collision detection in this series is much more in depth so it will help you build your concept.
You can create your own system too of course. If you have a concept of multiple lives, a collision could simply remove one life instead of closing the entire game.
This marks the end of the Pygame Sprite Collision Detection Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

report this ad
Detect Collisions in Pygame

There are several different ways of detecting collisions in Pygame, and this article will cover some of them.
Please enable JavaScript
The code displayed here is not the complete code for a valid Pygame window. If you are interested in a bare-bones framework, consult this article.
Detect Collisions Using rect.collidepoint() in Pygame
With the collidepoint() method of the rect class, we can test if a given point is inside the rect . This is useful on many occasions, for example, when you want some UI elements to change the look when hovering over them.
In this article, we have discussed the function and made a button with it. You can either supply the function with the x and y coordinate separately or provide them in an iterable like a tuple or list.
Detect Collisions Using rect.colliderect() in Pygame
With this function of the rect class, we can test whether any portion of another rect is within its bounds. Hence, we have to supply this function with another rect .
Detect Collisions Using rect.collidelist() or rect.collidelistall() in Pygame
We can also use the rect.collidelist() method, which receives a list of rects and tests if one intersects with the main rect . This function will return the first rect index, which collides with the rect .
The rect.collidelistall() method is similar and has only one key difference: it will return an array with all indices of rects that collide with the main rect .
Detect Collisions Using rect.collidedict() or rect.collidedictall() in Pygame
These methods are pretty much the same as the methods above, but they return the key and value pair of rects that collide with the main rect .
Hi, my name is Maxim Maeder, I am a young programming enthusiast looking to have fun coding and teaching you some things about programming.