How to make rect from the intersection of two?

血红的双手。 提交于 2020-01-03 03:40:21

问题


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:

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.

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?


回答1:


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);

(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);

Alternatively, you can use the clip() function. From the docs you linked in your question:

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.



来源:https://stackoverflow.com/questions/20484942/how-to-make-rect-from-the-intersection-of-two

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!