碰撞工作,但我不知道怎么知道collsiion方向

时间:2017-03-01 13:06:46

标签: c# collision-detection monogame tiled

我与我的地图发生碰撞碰撞工作但是当我的玩家发生碰撞时我停止了玩家的移动并且他不走路因为我不知道如何阻止玩家向一个方向移动

在播放器和地图下我的代码碰撞

public bool IsCollisionTile(Rectangle player)
{
    foreach(Rectangle rect in this._collisionObject)
    {
        if (rect.Intersects(player))
        {
            return true;
        }
    }
    return false;
}

播放器不移动的代码在Game1类中

if (mapLoader.IsCollisionTile(player.getDestinationRect()))
{
        player.setCantWalk(true);
}

它在Player.cs类中的函数update和setCantWalk

private bool _cantWalk;

    public void Update()
    {
    this._destinationRectangle.X = (int)_position.X;
    this._destinationRectangle.Y = (int)_position.Y;
    this._destinationRectangle.Width = _texture.Width;
    this._destinationRectangle.Height = _texture.Height;
    if(Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                if (_cantWalk == false)
                {
                    _position.Y--;
                }
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Down))
            {
                if (_cantWalk == false)
                {
                    _position.Y++;
                }
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                if (_cantWalk == false)
                {
                    _position.X++;
                }
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                if (_cantWalk == false)
                {
                    _position.X--;
                }
            }

        }

        public void setCantWalk(bool walk)
        {
            _cantWalk = walk;
        }

想帮助我

1 个答案:

答案 0 :(得分:0)

对于更简单的方法,您需要记录对象的移动。因此,在检查重叠时,您知道方向上的哪个移动导致重叠。然后,为该对象设置变量cantWalkX或cantWalkY。

更好的解决方案是检查碰撞表面以确定障碍物。这需要您更改交叉例程以返回交叉对象,并根据它们的相对位置,防止在该方向上移动。例如,如果碰撞对象位于对象的右侧,请设置cantWalkXPositive。如果左边有另一个,请将cantWalkXNegative设置为true等等......

相关问题