Search code examples
pythonpygamerect

How to know how many times my rectangle has collided with other rectangles in pygame?


There is a game where rectangles falls and we have to avoid them, if we collide once speed decreases by 1 , second time speed decreases by 2 and so on

How to find out how many times we collided


Solution

  • You would create a variable that counts the number of collisions and you would also need a function that detects whether a collision has occured. Here is an example where there is a variable "collisions" and the collision detection is calculated in the function touching_rect().

    collision = 0
    if touching_rect():
        colision += 1
        speed -= collision
    

    In this case the variable speed would keep track of how fast the rectangle is moving. Once there is a collision the speed would decrease by one. Next time there is a collision the speed would decrease by 2 and so on.

    note that after the speed has been decreased must then move the rectangle somewhere else so that you are not continuously slowing down the speed. This could be in another function you make such as reset_rectangle()

    collision = 0
    if touching_rect(): 
        colision += 1
        speed -= collision
        reset_rectangle()