2017-03-01 144 views
1

我已经做了与我的地图碰撞工作的碰撞,但是当我的球员有碰撞时,我停止球员的运动,他不走路,因为我不知道怎么的一个方向停止播放碰撞工作,但我不知道如何知道collsiion方向

玩家和图规定的我的代码碰撞

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

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; 
     } 

思帮我

+0

您可以尝试在X轴上移动您的播放器,进行碰撞检查,然后再按Y轴再次进行检查,然后将其中一个s)导致检查...似乎不理想,但它是一个选项 –

+0

你好,但我是一个初学者,我不知道该怎么办 –

回答

0

对于简单的方法的功能更新和setCantWalk,你需要保持你的对象的运动的记录。因此,在检查重叠时,您知道某个方向上的移动会导致重叠。然后,为该对象设置变量cantWalkX或cantWalkY。

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