Unity3D:按下一个键然后同时按下另一个键时如何改变力?

Unity3D: How do i change force when pressing 1 key then pressing another at the same time?

我想模拟一个简单的推力效果,例如(Lunar Land)。我想在按下向上箭头键时向上推,然后在按下适当的箭头键时向上推 left/right,但仍然保持按下。

  if (Input.GetKey(KeyCode.UpArrow))
     {
         thrust = (Vector3.up * thrustForce);
     }
     else if (Input.GetKey(KeyCode.LeftArrow))
     {
         thrust = (Vector3.left * thrustForce);
     }
     else if (Input.GetKey(KeyCode.RightArrow))
     {
         thrust = (Vector3.right * thrustForce);
     }
     else
     {
         thrust = (Vector3.zero);
     }        

这是我开始的,然后开始添加多个 "IF" 仍然没有正确移动的语句。基本上在下面,当我按下 UP 时,物体会向上推,但不会移动 left\right 直到我松开 UP 并再次按下 left\right。

我知道这可能是一个简单的代码问题

这行不通的原因是它只会执行其中一个语句,因为您有 else if。您需要像这样的纯 IF:

bool keyHold = false;

if (Input.GetKey(KeyCode.UpArrow))
{
    thrust = (Vector3.up * thrustForce);
    keyHold = true;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
    thrust = (Vector3.left * thrustForce);
    keyHold = true;
}
if (Input.GetKey(KeyCode.RightArrow))
{
    thrust = (Vector3.right * thrustForce);
    keyHold = true;
}

if(!keyHold) {
    thrust = (Vector3.zero);
}

这是一个非常简单的修复。您的代码当前在 if 内用于向上箭头,因为您使用 else ifs,代码甚至不会尝试检查其他箭头键。如果您没有坚持下去,那么它会检查左箭头,然后是右箭头,依此类推,如果按下其中一个键则停止并跳过之后的所有内容。

此外,因为你在推力上使用 =,ifs 中的语句也会覆盖之前的内容,这样如果你进入所有 ifs,只有最后达到的推力将是已应用,将覆盖您之前的设置。

因此,您有两个小问题:else ifs 和使用 = 而不是增加推力。一个可能的修复是这样的:

thrust = Vector3.Zero; //Start with zero

if (Input.GetKey(KeyCode.UpArrow))
{
    thrust += Vector3.up * thrustForce; //Add on up thrust
}
if (Input.GetKey(KeyCode.LeftArrow))
{
    thrust += Vector3.left * thrustForce; //Add on left thrust
}
if (Input.GetKey(KeyCode.RightArrow))
{
    thrust += Vector3.right * thrustForce; //Add on right thrust
}

如果你同时按住左右键,它们就会相互抵消,不需要任何检查。