[英]How to handle the 4 sides of rect object in case of intersectsWith another one?
我必須2個rect對象。 其中一個不能動,另一個可以動。 當它與每側的第一個相交時,我想處理。 就像是:
if (rect1.IntersectsWith(rect2))
{
if (rect1.Top == rect2.Bottom)
{
...
}
else if (rect1.Bottom == rect2.Top)
{
...
}
else if (rect1.Left == rect2.Right)
{
...
}
else if (rect1.Right == rect2.Left)
{
...
}
}
這給我一個不准確的結果。 任何想法?
看來您已經有了確定兩個矩形是否碰撞的方法,這很好,因為這使您的工作更加輕松。 您現在要做的就是確定碰撞發生在哪一側,然后采取相應的措施。
如果是這樣,那么您已經在正確的軌道上。 但是,您檢查的邏輯有些錯誤。 您正在檢查一個邊緣是否正好在另一邊緣的頂部 。 在大多數應用中,這實際上很少見。 您應該檢查的是是否存在任何重疊,您需要使用<=
和>=
比較器。
if (rect1.IntersectsWith(rect2))
{
// assumes that positive Y signifies downward direction
if (rect1.Top <= rect2.Bottom)
{
...
}
else if (rect1.Bottom >= rect2.Top)
{
...
}
else if (rect1.Left <= rect2.Right)
{
...
}
else if (rect1.Right >= rect2.Left)
{
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.