Collision Detection in PyGame
Last Updated :
15 Dec, 2022
Prerequisite: Introduction to 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
# import required libraries
import pygame
import random
# initialize pygame objects
pygame.init()
# define the colours
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
black = (0, 0, 0)
# set the Dimensions
width = 650
height = 700
# size of a block
pixel = 64
# set Screen
screen = pygame.display.set_mode((width,
height))
# set caption
pygame.display.set_caption("CORONA SCARPER")
# load the image
gameIcon = pygame.image.load("rectangleBlock.png")
# set icon
pygame.display.set_icon(gameIcon)
# load the image
backgroundImg = pygame.image.load("wallBackground.jpg")
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
# load the image
playerImage = pygame.image.load("player.png")
# set the position
playerXPosition = (width/2) - (pixel/2)
# So that the player will be
# at height of 20 above the base
playerYPosition = height - pixel - 10
# set initially 0
playerXPositionChange = 0
# define a function for setting
# the image at particular
# coordinates
def player(x, y):
# paste image on screen object
screen.blit(playerImage, (x, y))
# load the image
blockImage = pygame.image.load("rectangleBlock.png")
# set the random position
blockXPosition = random.randint(0,
(width - pixel))
blockYPosition = 0 - pixel
# set the speed of
# the block
blockXPositionChange = 0
blockYPositionChange = 2
# define a function for setting
# the image at particular
# coordinates
def block(x, y):
# paste image on screen object
screen.blit(blockImage,
(x, y))
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
Now,
Horizontal Collision
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.
Vertical Collision
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
# define a function for
# collision detection
def crash():
# take a global variable
global blockYPosition
# check conditions
if playerYPosition < (blockYPosition + pixel):
if ((playerXPosition > blockXPosition
and playerXPosition < (blockXPosition + pixel))
or ((playerXPosition + pixel) > blockXPosition
and (playerXPosition + pixel) < (blockXPosition + pixel))):
blockYPosition = height + 1000
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.
Part 4:
Python3
running = True
while running:
# set the image on screen object
screen.blit(backgroundImg, (0, 0))
# loop through all events
for event in pygame.event.get():
# check the quit condition
if event.type == pygame.QUIT:
# quit the game
pygame.quit()
# movement key control of player
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
playerXPositionChange = 3
if event.key == pygame.K_LEFT:
playerXPositionChange = -3
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or pygame.K_LEFT:
playerXPositionChange = 0
This is the gaming loop where the movement of the player is controlled. and the game is started.
Part 5:
Python3
# Boundaries to the Player
# if it comes at right end,
# stay at right end and
# does not exceed
if playerXPosition >= (width - pixel):
playerXPosition = (width - pixel)
# if it comes at left end,
# stay at left end and
# does not exceed
if playerXPosition <= 0:
playerXPosition = 0
These are the boundaries to the player so that when the player moves to its rightmost or leftmost position on the screen, it should not go further and bounce back.
Part 6:
Python3
# Multiple Blocks Movement after each other
# and condition used because of game over function
if (blockYPosition >= height - 0 and
blockYPosition <= (height + 200)):
blockYPosition = 0 - pixel
# randomly assign value in range
blockXPosition = random.randint(0, (width - pixel))
When the block without colliding goes away from the player, then we need to let him come again from the top. Hence we provide a condition that if the block's Y position is below the height of the screen and below height+200(as above 1000+, the block appears when the block has collided), then move it again at the top.
Part 7:
Python3
# movement of Player
playerXPosition += playerXPositionChange
# movement of Block
blockYPosition += blockYPositionChange
# player Function Call
player(playerXPosition, playerYPosition)
# block Function Call
block(blockXPosition, blockYPosition)
# crash function call
crash()
# update screen
pygame.display.update()
At the last, the movement of the player and the block is given and the screen is refreshed
Output:
Similar Reads
PyGame Tutorial Pygame is a free and open-source library for making games and multimedia applications in Python. It helps us create 2D games by giving us tools to handle graphics, sounds and user input (like keyboard and mouse events) without needing to dig deep into complex stuff like graphics engines.Release date
7 min read
Introduction
Getting Started
PyGame - Import and InitializeIn this article, we will see how to import and initialize PyGame. Installation The best way to install pygame is with the pip tool, we can install pygame by using the below command: pip install pygameImporting the Pygame library To import the pygame library, make sure you have installed pygame alrea
2 min read
How to initialize all the imported modules in PyGame?PyGame is Python library designed for game development. PyGame is built on the top of SDL library so it provides full functionality to develop game in Python. Pygame has many modules to perform it's operation, before these modules can be used, they must be initialized. All the modules can be initial
2 min read
How to create an empty PyGame window?Pygame window is a simple window like any other window, in which we display our game screen. It is the first task we do so that we can display our output onto something. Our main goal here is to create a window and keep it running unless the user wants to quit. To perform these tasks first we need t
2 min read
How to get the size of PyGame Window?In this article, we will learn How to get the size of a PyGame Window. Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game
1 min read
Allowing resizing window in PyGameIn this article, we will learn How to allow resizing a PyGame Window. Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game
2 min read
How to change screen background color in Pygame?Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Functions Used: pygame.init(): This function is used to initialize all the pygame
1 min read
How to Change the Name of a Pygame window?PyGame window is a simple window that displays our game on the window screen. By default, pygame uses "Pygame window" as its title and pygame icon as its logo for pygame window. We can use set_caption() function to change the name and set_icon() to set icon of our window. To change the name of pygam
2 min read
How to set up the Game Loop in PygGame ?In this article, we will see how to set up a game loop in PyGame. Game Loop is the loop that keeps the game running. It keeps running till the user wants to exit. While the game loop is running it mainly does the following tasks: Update our game window to show visual changesUpdate our game states ba
3 min read
How to change the PyGame icon?While building a video game, do you wish to set your image or company's logo as the icon for a game? If yes, then you can do it easily by using set_icon() function after declaring the image you wish to set as an icon. Read the article given below to know more in detail. Syntax: pygame_icon = pygame
2 min read
Pygame - SurfaceWhen using Pygame, surfaces are generally used to represent the appearance of the object and its position on the screen. All the objects, text, images that we create in Pygame are created using surfaces. Creating a surface Creating surfaces in pygame is quite easy. We just have to pass the height an
6 min read
Pygame - TimeWhile using pygame we sometimes need to perform certain operations that include the usage of time. Like finding how much time our program has been running, pausing the program for an amount of time, etc. For operations of this kind, we need to use the time methods of pygame. In this article, we will
4 min read
Drawing Shapes
Event Handling
Working with Text
Working with images
Python | Display images with PyGamePygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, itâs up to the imagination or necessity of the developer, what type of game he/she wants to develop usin
2 min read
Getting width and height of an image in PygamePrerequisites: Pygame To use graphics in python programs we use a module called Pygame. Pygame provides high functionality for developing games and graphics in Python. Nowadays Pygame are very much popular to build simple 2D games. In order to run a program written in Python using Pygame module, a s
3 min read
How to Rotate and Scale images using PyGame ?In this article, we are going to see how to Rotate and Scale the image. Image Scaling refers to the resizing of the original image and Image Rotation refers to turning off an image with some angle. Rotations in the coordinate plane are counterclockwise. Let's proceed with the methods used and the co
3 min read
Pygame - Flip the imageIn this article, we are going to see how images can be flipped using Pygame. To flip the image we need to use pygame.transform.flip(Surface, xbool, ybool) method which is called to flip the image in vertical direction or horizontal direction according to our needs. Syntax: pygame.transform.flip(Surf
2 min read
How to move an image with the mouse in PyGame?Pygame is a Python library that is used to create cross-platform video games. The games created by Pygame can be easily run through any of the input devices such as a mouse, keyboard, and joystick. Do you want to make a game that runs through mouse controls? Don't you know how to move the image with
4 min read
How to use the mouse to scale and rotate an image in PyGame ?In this article, we will discuss how to transform the image i.e (scaling and rotating images) using the mouse in Pygame. Approach Step 1: First, import the libraries Pygame and math. import pygame import math from pygame.locals import * Step 2: Now, take the colors as input that we want to use in th
5 min read
PyGame Advance
How to create Buttons in a game using PyGame?Pygame is a Python library that can be used specifically to design and build games. Pygame only supports 2D games that are build using different shapes/images called sprites. Pygame is not particularly best for designing games as it is very complex to use and lacks a proper GUI like unity gaming eng
3 min read
Python - Drawing design using arrow keys in PyGamePygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, itâs up to the imagination or necessity of developer, what type of game he/she wants to develop using th
3 min read
Moving an object in PyGame - PythonTo make a game or animation in Python using PyGame, moving an object on the screen is one of the first things to learn. We will see how to move an object such that it moves horizontally when pressing the right arrow key or left arrow key on the keyboard and it moves vertically when pressing up arrow
2 min read
Python | Making an object jump in PyGamePygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, itâs up to the imagination or necessity of developer, what type of game he/she wants to develop using th
3 min read
Adding Boundary to an Object in PygameBoundaries to any game are very important. In snake games, space invaders, ping pong game, etc. the boundary condition is very important. The ball bounces at the boundaries of the screen in ping pong games. So, the idea behind this boundaries is to change the position of the ball or object in revers
5 min read
Collision Detection in PyGamePrerequisite: Introduction to 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 thi
7 min read
Pygame - Creating SpritesSprites are objects, with different properties like height, width, color, etc., and methods like moving right, left, up and down, jump, etc. In this article, we are looking to create an object in which users can control that object and move it forward, backward, up, and down using arrow keys. Let fi
2 min read
Pygame - Control SpritesIn this article, we will discuss how to control the sprite, like moving forward, backward, slow, or accelerate, and some of the properties that sprite should have. We will be adding event handlers to our program to respond to keystroke events, when the player uses the arrow keys on the keyboard we w
4 min read
How to add color breezing effect using pygame?Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use and doesnât have a proper GUI like unity but it definitely builds
2 min read
Python | Playing audio file in PygameGame programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doin
2 min read
Exercise, Applications, and Projects
Snowfall display using Pygame in PythonNot everybody must have witnessed Snowfall personally but wait a minute, What if you can see the snowfall right on your screen by just a few lines of creativity and Programming.  Before starting the topic, it is highly recommended revising the basics of Pygame. Steps for snowfall creation 1. Import
3 min read
Rhodonea Curves and Maurer Rose in PythonIn this article, we will create a Rhodonea Curve and Maurer Rose pattern in Python! Before we proceed to look at what exactly is a rhodonea curve or maurer rose we need to get the basic structure of our program ready! Basic Structure of the Program - Before we move on to learn anything about Rhodon
7 min read
Creating start Menu in PygamePygame is a Python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different shapes or sprites. Pygame doesn't have an in-built layout design or any in-built UI system this means there is no easy way to make UI or levels for a game.
3 min read
Tic Tac Toe GUI In Python using PyGameThis article will guide you and give you a basic idea of designing a game Tic Tac Toe using pygame library of Python. Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming l
15+ min read
Snake Game in Python - Using Pygame moduleSnake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginne
15+ min read
8-bit game using pygamePygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use doesnât have a proper GUI like unity but it definitely builds log
9 min read
Bubble sort visualizer using PyGameIn this article we will see how we can visualize the bubble sort algorithm using PyGame i.e when the pygame application get started we can see the unsorted bars with different heights and when we click space bar key it started getting arranging in bubble sort manner i.e after every iteration maximum
3 min read
Ternary Search Visualization using Pygame in PythonAn algorithm like Ternary Search can be understood easily by visualizing. In this article, a program that visualizes the Ternary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any s
5 min read
Sorting algorithm visualization : Heap SortAn algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach: Generate random array and fill the pygame window wi
4 min read
Sorting algorithm visualization : Insertion SortAn algorithm like Insertion Sort can be understood easily by visualizing. In this article, a program that visualizes the Insertion Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in python using pygame library. Approach: Generate random array and fill the pygame
3 min read
Binary Search Visualization using Pygame in PythonAn algorithm like Binary Search can be understood easily by visualizing. In this article, a program that visualizes the Binary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sor
4 min read
Building and visualizing Sudoku Game Using PygameSudoku is a logic-based, combinatorial number-placement puzzle. The objective is to fill a 9Ã9 grid with digits so that each column, each row, and each of the nine 3Ã3 subgrids that compose the grid contain all of the digits from 1 to 9. We will be building the Sudoku Game in python using pygame li
7 min read
Create Bingo Game Using PythonA card with a grid of numbers on it is used to play the popular dice game of bingo. Players check off numbers on their cards when they are selected at random by a caller, competing to be the first to mark off all of their numbers in a particular order. We'll examine how to utilise Python to create a
9 min read
Create Settings Menu in Python - PygamePython is a flexible programming language with a large selection of libraries and modules for a variety of applications. Pygame menu is one such toolkit that enables programmers to design graphical user interfaces for games and apps. In this tutorial, we'll look at how to use the pygame menu package
9 min read
Car Race Game In PyGameIn this article, we will see how to create a racing car game in Python using Pygame. In this game, we will have functionality like driving, obstacle crashing, speed increment when levels are passed, pause, countdown, scoreboard, and Instruction manual screen. Required Modules: Before going any furt
15+ min read
Spiral Sprint Game in Python Using PygameIn this article, we will see how to create a spiral sprint game in Python using Pygame. In this game, we will have functionality like difficulty modes, obstacle crashing, speed increment when points are increased, scoreboard, Particle animation, color-changing orbits, coins, and game sounds. Spiral
15+ min read
Selection sort visualizer using PyGameIn this article, we will see how to visualize Selection sort using a Python library PyGame. It is easy for the human brain to understand algorithms with the help of visualization. Selection sort is a simple and easy-to-understand algorithm that is used to sort elements of an array by dividing the ar
3 min read
Mouse Clicks on Sprites in PyGameThe interactiveness of your game can be significantly increased by using Pygame to respond to mouse clicks on sprites. You may develop unique sprite classes that manage mouse events and react to mouse clicks with the aid of Pygame's sprite module. This article will teach you how to use Pygame to mak
3 min read
Slide Puzzle using PyGame - PythonSlide Puzzle game is a 2-dimensional game i.e the pieces can only be removed inside the grid and reconfigured by sliding them into an empty spot. The slide puzzle game developed here is a 3X3 grid game i.e 9 cells will be there from 1 to 8(9 is not here since a blank cell is needed for sliding the n
14 min read
Brick Breaker Game In Python using PygameBrick Breaker is a 2D arcade video game developed in the 1990s. The game consists of a paddle/striker located at the bottom end of the screen, a ball, and many blocks above the striker. The basic theme of this game is to break the blocks with the ball using the striker. The score is calculated by th
14 min read
Hover Button in PygameHere, we will talk about while hovering over the button different actions will perform like background color, text size, font color, etc. will change. In this article we are going to create a button using the sprites Pygame module of Python then, when hovering over that button we will perform an eve
6 min read
Create a Pong Game in Python - PygamePong is a table tennis-themed 2-player 2D arcade video game developed in the early 1970s. The game consists of two paddles/strikers, located at the left and right edges of the screen, and a ball. Create a Pong Game in PythonThe basic theme of this game is to make sure that the ball doesn't hit the w
10 min read
Save/load game Function in PygamePygame is a free-to-use and open-source set of Python Modules. Â And as the name suggests, it can be used to build games, and to save game data or the last position of the player you need to store the position of the player in a file so when a user resumes the game its game resumes when he left. In t
4 min read