如何从两个的交点制作矩形? [英] How to make rect from the intersection of two?
问题描述
我正在研究一个突破克隆,我一直在试图弄清楚如何获得两个碰撞矩形的交集矩形,以便我可以测量球在 x 轴和 y 轴上进入块的深度并决定哪个我将反转的速度的分量.
I'm working on a breakout clone and I've been trying to figure out how to get the intersection rect of two colliding rects so I can measure how deep the ball entered the block in both x and y axis and decide which component of the velocity I'll reverse.
我想我可以像这样计算每种情况的深度:
I figured I could calculate the depth for each case like this:
但是如果我有交叉点,那么我就不必担心球是从左/右或顶部/底部击中挡块(因为我只会分别反转 x 和 y 轴),从而节省了我很多打字时间.
But if I had the intersection rect than I woudn't have to worry if the ball hits the block from the left/right or top/bottom (since I would be only reversing the x and y axis respectively), thus saving me a lot of typing.
我查看了 Pygame 的文档 但似乎没有有一个功能.我将如何解决这个问题?
I've looked on Pygame's docs but seems it doesn't have a function for that. How would I go about solving this problem?
推荐答案
假设您有矩形 r1
和 r2
,带有 .left, .right, .顶部和底部
边缘,然后
Assuming you have rectangles r1
and r2
, with .left, .right, .top, and .bottom
edges, then
left = max(r1.left, r2.left);
right = min(r1.right, r2.right);
top = max(r1.top, r2.top);
bottom = min(r1.bottom, r2.bottom);
(通常的惯例是坐标从上到下从左到右增加).最后,检查 left
top
(with the usual convention that coordinates increase top to bottom and left to right). Finally, check that left<right
and top<bottom
, and compute the area:
Area = (right - left) * (top - bottom);
或者,您可以使用 clip()
函数.从您在问题中链接的文档:
Alternatively, you can use the clip()
function. From the docs you linked in your question:
clip(Rect) -> Rect 返回一个裁剪成的新矩形完全在参数 Rect 内.如果两个矩形不重叠开始,返回大小为 0 的 Rect.
clip(Rect) -> Rect Returns a new rectangle that is cropped to be completely inside the argument Rect. If the two rectangles do not overlap to begin with, a Rect with 0 size is returned.
这篇关于如何从两个的交点制作矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!