【问题标题】:Unity3D: How do i change force when pressing 1 key then pressing another at the same time?Unity3D:按下一个键然后同时按下另一个键时如何改变力度?
【发布时间】:2017-07-27 18:15:26
【问题描述】:

我想模拟一个简单的类似推力的效果,例如(月球土地)。我想在按下向上箭头键时向上推,然后在按下相应的箭头键时向左/向右推,但仍要保持向上。

  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 时,对象会向上推,但不会向左\右移动,直到我放开 UP 并再次按左\右。

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

【问题讨论】:

  • 删除“else”并将它们放在单独的 if 语句中。这将允许它响应多个输入。

标签: c# unity3d keypress


【解决方案1】:

这不起作用的原因是它只会执行其中一个语句,因为你有和 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);
}

【讨论】:

    【解决方案2】:

    这是一个非常简单的修复。您的代码当前位于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
    }
    

    如果你同时按住左和右,它们只是相互抵消,而不需要任何检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 2014-03-07
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多