C# 二维碰撞检测问题

标签 c# gdi+ 2d collision-detection

我一直在试图弄清楚如何改变我的碰撞检测以使其正常工作,我将所有墙对象堆叠在一个列表中,然后当玩家移动时我循环遍历每个墙对象并调用 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 坐标并检查它们是否与墙壁发生碰撞,如果它们什么也没发生,否则我移动玩家。

但我注意到它不能正常工作,如果我在游戏区内添加一 block 墙,它只会检查右下角的碰撞检测吗?

玩家移动方式:

        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 == 高度。

关于C# 二维碰撞检测问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1298999/

相关文章:

c# - 用\\替换\不适用于特定变量

c# - 困惑。 SmoothingMode.AntiAlias 和 SmoothingMode.HighQuality 之间的区别

c# - 测量包裹的字符串

javascript - 绘制一个没有线边框的空心圆

c - 二维 R2C FFTW : Order of Fourier coefficients

javascript - 在 javascript 中使用 Html.DropDownList

c# - 使用 foreach 创建包含 2 列的列表

c# - Google Maps.TimeZone.Query LatLng 返回不正确的时间偏移

c++ - 如何在透明背景上绘制PNG?

c# - 在网格布局中创建动态按钮 - 创建幻方 UI