簡體   English   中英

2D Monogame:矩形碰撞檢測,側面特定

[英]2D Monogame: Rectangle collision detection, side specific

我有兩個矩形,一個玩家,一張地圖。 玩家無需走過地圖。 播放器和地圖都有一個帶有位置和紋理的寬度和高度的矩形,也都有一個Vector位置。 Rectangle.Intersect()僅輸出一個布爾值,我無法弄清楚如何找出與哪一側發生碰撞。 我在這里找到了此函數,該函數輸出一個Vector,代表矩形重疊的數量。

public static Vector2 GetIntersectionDepth(this Rectangle rectA,                 Rectangle rectB)
    {
        // Calculate half sizes.
        float halfWidthA = rectA.Width / 2.0f;
        float halfHeightA = rectA.Height / 2.0f;
        float halfWidthB = rectB.Width / 2.0f;
        float halfHeightB = rectB.Height / 2.0f;

        // Calculate centers.
        Vector2 centerA = new Vector2(rectA.Left + halfWidthA, rectA.Top + halfHeightA);
        Vector2 centerB = new Vector2(rectB.Left + halfWidthB, rectB.Top + halfHeightB);

        // Calculate current and minimum-non-intersecting distances between centers.
        float distanceX = centerA.X - centerB.X;
        float distanceY = centerA.Y - centerB.Y;
        float minDistanceX = halfWidthA + halfWidthB;
        float minDistanceY = halfHeightA + halfHeightB;

        // If we are not intersecting at all, return (0, 0).
        if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
            return Vector2.Zero;

        // Calculate and return intersection depths.
        float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
        float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
        return new Vector2(depthX, depthY);
    }

此函數將根據邊給出負數,但是我無法弄清楚如何有效地使用它們。 我試過了:

Vector2 overlap =   RectangleExtensions.GetIntersectionDepth(map.Dungeon[x,y].BoundingBox, player.BoundingBox);
if (overlap.X > 0) //This should be collision on the left
{
    //Move the player back
}

但是,這會引起一些奇怪的錯誤,尤其是在嘗試將Y播放器和地圖值設置為相同的錯誤時。

問題:在單機游戲中如何使用矩形功能(使用此功能或其他方式使您知道與哪一側發生碰撞)進行碰撞檢測。

謝謝你的幫助!

XNA中的Rectangle類具有4個可以在此處使用的屬性:

底部

您可以使用它們來確定碰撞發生在哪一側。

例如,考慮Player.Rectangle.Left > Map.Rectangle.Left 如果這是真的,則碰撞可能發生在右側(假設玩家的左側在X軸上的距離大於地圖的左側,這意味着玩家在地圖上最左側的點的右側地圖)。

基本上,您可以比較兩個矩形的X和Y坐標。 除了奇怪的情況(例如一個矩形完全淹沒在另一個矩形中,或者一個矩形是另一個矩形的超集)之外,這些還應該足以告訴您它們碰撞的一側。

一種更好的檢查方法是通過具有兩個形狀的中點,這也可能是一種更簡單的方法來判斷兩個對象的相對位置。

現在,即使它是3D模式,您也可能會發現這篇文章很有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM