【问题标题】:Collision with sprites using intersects使用相交与精灵碰撞
【发布时间】:2018-01-21 19:29:35
【问题描述】:

我正在处理 XNA 上的游戏任务,我正在尝试找出当我的玩家精灵走进一个岩石精灵时如何使用带有相交的 if 语句来阻止他。当他走进岩石精灵时,我尝试将玩家速度设置为 0,但随后他被卡在他的位置并且无法移动。我该如何正确地做到这一点?

【问题讨论】:

  • 如果您提供代码摘录会很有帮助

标签: c# xna


【解决方案1】:

如果不查看您的代码,很难找出问题所在,但根据您的说法,我认为这可能是原因:

假定更新

int speed = 0;
Vector2 pos;
protected override void Update(GameTime gameTime)
{
    if (Keyboard.GetState().IsKeyDown(Keys.Escape))
    {
        Exit();
    }
    k = Keyboard.GetState();        // Get New States
    m = Mouse.GetState();
    speed = 0;                      // Reset Speed

    if(k.IsKeyDown(Keys.D)) 
    {
        speed = 3; 
    }
    // Similar code for A (but negative)

    if(Collides(pos, rockPos)) // whatever your intersect condition is
    {
        speed = 0;
    }
    pos.x += speed;
    base.Update(gameTime);
}

上面代码的问题是你将速度设置为0与岩石物体碰撞后。如果是这种情况,一旦用户撞到了一块石头,即使他们试图退出,您的代码也会将其检测为碰撞并将他们困在里面!!

为了解决这个问题,我们在将玩家移动到新位置之前检查玩家是否会发生碰撞

Vector2 futurePos = pos;
futurePos.x += speed;
if(Collides(futurePos, rockPos))
{
    speed = 0;  // Will set speed to 0 BEFORE collision 
}

pos.x += speed;

【讨论】:

  • 感谢详细的代码和回复!非常感谢。
  • 不用担心@orekideki :)。如果我的回复有帮助,请将其标记为正确:P 谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 2012-03-04
  • 1970-01-01
相关资源
最近更新 更多