0
votes

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.

1
Get the coordinates of both objects and check how they are related. It depends on how fine an answer you want, but if you only think in say 1D, then if you know there's a collision, you can check the relation of their x coordinates to see which side of the obsticle is the character.fbence
Btw, as this is your first question: you should read a bit about how to ask nice questions, i.e. post relevant code etc. It is a lot easier to help, if people actually know what you need help with :)fbence
@fbence thanks for the reply, tho how can i get the specific obstacle which collided out of the group?nighmared
@fbence Sure, i just couldn't think of any code parts that would've been to helpfulnighmared
Maybe part of you code that defines the obsticles, and the part that detects the collision might be useful. There are a few methods that can do this in pygame. Also, if you think that the comments are narrowing down your actual question (i.e. you are really interested in gettting which object the collision occured with etc.) you can edit your question.fbence

1 Answers

1
votes

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.