2015-05-03 35 views
0

好吧,你说你玩的是自上而下的游戏。您按WD进入正确的方向。现在你只是想正确的,所以你释放W键。人们会希望你然后改变方向并向右转,但相反,你继续向右。我能做些什么来解决这个问题? 这里是我的代码:XNA Diagonal Movement Key Release

 if (kb.IsKeyDown(Keys.W) || kb.IsKeyDown(Keys.A) || kb.IsKeyDown(Keys.S) || kb.IsKeyDown(Keys.D)) 
     { 
      if (kb.IsKeyDown(Keys.W)) 
       velocity.Y = -movespeed; 
      else if (kb.IsKeyDown(Keys.A)) 
       velocity.X = -movespeed; 
      else if (kb.IsKeyDown(Keys.S)) 
       velocity.Y = movespeed; 
      else if (kb.IsKeyDown(Keys.D)) 
       velocity.X = movespeed; 
      else if (kb.IsKeyDown(Keys.W) && kb.IsKeyDown(Keys.D)) 
      { 
       velocity.X = movespeed; 
       velocity.Y = -movespeed; 
      } 
      else if (kb.IsKeyDown(Keys.W) && kb.IsKeyDown(Keys.A)) 
      { 
       velocity.X = -movespeed; 
       velocity.Y = -movespeed; 
      } 
      else if (kb.IsKeyDown(Keys.S) && kb.IsKeyDown(Keys.D)) 
      { 
       velocity.X = movespeed; 
       velocity.Y = movespeed; 
      } 
      else if (kb.IsKeyDown(Keys.S) && kb.IsKeyDown(Keys.A)) 
      { 
       velocity.X = -movespeed; 
       velocity.Y = movespeed; 
      } 
     } 
     else 
      velocity *= .9f; 

     position += velocity; 

回答

0

所以我经过几个小时的斗争后自己想出了答案。

只需在检查前将速度设置为零: 编辑:乘以.89实际上是为了更平滑的运动。

 if (kb.IsKeyDown(Keys.W) || kb.IsKeyDown(Keys.A) || kb.IsKeyDown(Keys.S) || kb.IsKeyDown(Keys.D)) 
     { 
      velocity *= .89f 
      if (kb.IsKeyDown(Keys.W)) 
       velocity.Y = -movespeed; 
      if (kb.IsKeyDown(Keys.A)) 
       velocity.X = -movespeed; 
      if (kb.IsKeyDown(Keys.S)) 
       velocity.Y = movespeed; 
      if (kb.IsKeyDown(Keys.D)) 
       velocity.X = movespeed; 
     } 
     else 
      velocity *= .9f; 
+0

您是否认为对角线速度比向上/向下/向左/向右移动要快?一种解决方案是使速度正常化,然后乘以速度。另一种是如果运动是对角的,则用'sqrt(2)'分割速度。 –

+0

不,我没有。你能详细说明一下吗? – omni

+0

对角线速度将是'速度幅度* sqrt(2)'。 – snahor