如何知道与其他 Rect 碰撞的 pygame.Rect 的一侧? [英] how to know pygame.Rect's side that collide to other Rect?

查看:46
本文介绍了如何知道与其他 Rect 碰撞的 pygame.Rect 的一侧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pygame,python3.9,我想返回哪一侧(rect1)与rect2相撞.我已经尝试过这个,但它不起作用.我只想要内部模块和 pygame.(抱歉英语不好)

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

推荐答案

碰撞的一侧取决于相对的运动方向.相对运动是rect1rect2的运动差.

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"

这篇关于如何知道与其他 Rect 碰撞的 pygame.Rect 的一侧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆