簡體   English   中英

C#2D碰撞檢測問題

[英]C# 2D collision detection problem

我一直在試圖弄清楚如何更改碰撞檢測以使其正常工作,我將所有牆壁對象堆疊在一個List中,然后當玩家移動我循環通過每個牆壁對象並調用DetectCollision方法時,此方法返回true或false取決於物體是否在牆壁內。

牆檢測碰撞(X和Y坐標是牆的位置)

public bool DetectCollision(float x, float y)
    {
        if ((x >= this.XCoordinate && x <= (this.XCoordinate + this.BlockWidth)) && (y >= this.YCoordinate && y <= (this.YCoordinate + this.BlockHeight)))
            return true;            
        else
            return false;
    }

因此,在我的播放器功能中,當播放器嘗試移動時,我將移動添加到臨時的X,Y坐標中,並檢查這些碰撞是否撞在牆上,如果它們什么也不做,否則我將移動播放器。

但是我已經注意到它無法正常工作,如果我在游戲場內添加一塊牆,它只會檢查右下角的碰撞檢測?

玩家移動方式:

        float x, y;
        if (direction == Direction.E)
        {
            x = LiveObjects.player.XCoordinate - MovementSpeed;
            y = LiveObjects.player.YCoordinate;
        }
        else if (direction == Direction.W)
        {
            x = LiveObjects.player.XCoordinate + MovementSpeed;
            y = LiveObjects.player.YCoordinate;
        }
        else if (direction == Direction.N)
        {
            x = LiveObjects.player.XCoordinate;
            y = LiveObjects.player.YCoordinate - MovementSpeed;
        }
        else
        {
            x = LiveObjects.player.XCoordinate;
            y = LiveObjects.player.YCoordinate + MovementSpeed;
        }

        if (GameMechanics.DetectWallCollision(x, y) || GameMechanics.DetectWallCollision((x + LiveObjects.player.BlockWidth), (y + LiveObjects.player.BlockHeight))
        {
            OnPlayerInvalidMove(null, new PlayerEventArgs());
            return;
        }

而DetectWallCollision的循環就是:

foreach (Wall wall in LiveObjects.walls)
        {
            if (wall.DetectCollision(x, y))
                return true;
        }
        return false;

有任何想法嗎?

我假設您的世界中沒有任何事物是無限小的(即像素大小)。 為了實現真正的邊界框碰撞,您必須考慮兩個對象的大小,而不僅僅是一個。

boolean intersectsEntity(Entity e)
{
    return (e.position.x <= position.x + size.x) &&
           (e.position.y <= position.y + size.y) &&
           (e.position.x + e.size.x >= position.x) &&
           (e.position.y + e.size.y >= position.y);
}

當然,這是假設一個實體為其位置和大小具有向量。 因此size.x ==寬度,size.y ==高度。

有件事讓我感到困擾,您說過DetectCollision方法可以獲取牆的位置-但是,如果我正確解釋了您的代碼,則可以將x和y參數(即玩家和手的位置(移動后))傳遞給DetectWallCollision該位置下降到DetectCollision方法...

您是否已調試代碼以查看將哪些坐標傳遞給碰撞方法並跟蹤了if語句的運行路線?

如果由於某種原因無法調試代碼-編寫跟蹤文件-我認為解決方案將落在您的腿上;)

您的東方和西方走錯了路。 在左上角的坐標系為0,0的情況下,當您向下或向右移動時,該坐標系會正向增加,那么,西移通常意味着向左移動,這意味着X的值減小,而東向則相反。 您正在相反。

暫無
暫無

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

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