I recently have run into a problem with a simple collision detection test in my Pygame project. I am purposely not using the Sprite
class and some of the built in collision functions provided by Pygame for learning purposes. The problem I am having is not that the collisions aren't detected. The problem is that the collisions are lasting longer than they should be.
If you run my code, you will see that the Obstacle
objects randomly falling down the screen pass through the Player
object for some time, even after they have disappeared. collisions
counts the number of coordinates that the Obstacle
passes through Player
, which seems to typically be in-between -17 to -21. Why is this happening? Since the boolean obstacle.exists = False
is stated, shouldn't the Obstacle
object be instantly destroyed before it has time to pass through Player
-17 to -21 intersecting coordinates? Could this possibly be caused by an fps issue?? Basically, what I am trying to figure out is how to get Obstacle
to be destroyed instantly upon collision, so that collisions
only subtracts once.
Your collision detection is made regardless of the existence of an obstacle. You should add obstacles.exists
as first test on your collision détection:
if (obstacles.exists and
obstacles.x < player.x + player.w and
obstacles.x + obstacles.w > player.x and
obstacles.y < player.y + player.h and
obstacles.h + obstacles.y > player.y):
#do stuff
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.