I am using pygame, python3.9, I want to make to return which side(rect1) is collided with rect2.
I’ve already tried this but it dosen’t work. I just want internal module and pygame.(sorry for bad english)
def side(rect1, rect2):
direction = ""
if rect1.midtop[1] > rect2.midtop[1]:
direction = "top"
if rect1.midleft[0] > rect2.midleft[0]:
direction = "left"
if rect1.midright[0] < rect2.midright[0]:
direction = "right"
if rect1.midbottom[1] < rect2.midbottom[1]:
direction = "bottom"
return direction
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The side of the collision depends on the relative moving direction. The side of the collision depends on the relative movement of rect1 and rect2.
Anyway, you can estimate the side by calculating the difference in object position and finding the side with the minimum distance:
dr = abs(rect1.right - rect2.left)
dl = abs(rect1.left - rect2.right)
db = abs(rect1.bottom - rect2.top)
dt = abs(rect1.top - rect2.bottom)
if min(dl, dr) < min(dt, db):
direction = "left" if dl < dr else "right"
else:
direction = "bottom" if db < dt else "top"
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0