简体   繁体   中英

Pygame - detect collision direction

So i started some kinda big pygame project, everything went more or less well.

But now i'm really stuck at how to detect the directions of collisions.

So i got my character (2d sidescroller), and a sprite group for the obstacles which are by now all rects. Now however collision detection works fine, but is, and if it is then how, it possible to detect on which side of the obstacle rects the character rect collides with it?


Addition in case someone stumbles upon this question : The janky solution I ended up implementing used a "scaffolding" of four (invisible) lines per obstacle, one for each side. Once a collision with a specific obstacle was detected I looked up the four lines around the colliding rectangle in a dict and then went to check which of these lines was currently colliding with the player sprite. It kind of worked but the whole project was a mess anyway.

There are many 2D physics libraries that including collision detection and usually a large project like you said would require other physics like constraints, ray casting and bodies. A great library for python is pyBox2D and has good documentation on their github . pyBox2D will also fully handle collisions for you but you can also setup custom collision handlers.
For you question you ask how to check which position a rect collides with, you can do this using the pygame.Rect variables that are given like so

import pygame


def determineSide(rect1, rect2):
    if rect1.midtop[1] > rect2.midtop[1]:
        return "top"
    elif rect1.midleft[0] > rect2.midleft[0]:
        return "left"
    elif rect1.midright[0] < rect2.midright[0]:
        return "right"
    else:
        return "bottom"

rect1 = pygame.Rect(100, 100, 20, 20)
rect2 = pygame.Rect(100, 90, 20, 20)
print(determineSide(rect1, rect2))  

Note this does not check for collision but simply checks where rect2 is relative to rect1.

Maybe you can check which one or two of the four corners on one Rect are inside the other. There is one problem, though - if the Rect s are touching by the corners, it's up to the rest of the program what to do then. I haven't written a code snippet for this myself, but I'm working on a platformer as well and plan to create one.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM