Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

python - how to know pygame.Rect's side that collide to other Rect?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The side of the collision depends on th relatuve moving direction. The relative movment is the difference of the movement of rect1 and rect2.

Anyway, you can try to compute the difference of the on each side and to find the distance with the minimum amount:

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...