【问题标题】:Unity return rotation to 0 after button release松开按钮后,Unity 将旋转返回到 0
【发布时间】:2020-07-24 16:15:13
【问题描述】:

我有一个我写的小游戏,其中我有一个向前移动和左右转动的物体。当用户按下 A 对象向左旋转如果用户按下 D 它向左旋转并向左旋转,我在用户放开键后将旋转设置为 0

bool slowbtn = Input.GetKey("s");
bool right = Input.GetKey("d");

if (right == true)
{
    rd.AddForce(sideForce * Time.deltaTime, 0, 0,ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, 10 , 0);
}
if (Input.GetKey("a"))
{
    rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, -10 , 0);
}

如果我想在用户释放键时将旋转设置回 0 我正在使用这个

if (Input.GetButtonUp("a"))
{
    rd.transform.eulerAngles = new Vector3(0, 0, 0);
}
if (Input.GetButtonUp("d"))
{
    rd.transform.eulerAngles = new Vector3(0, 0, 0);
}

但它不起作用,我不明白为什么,它还破坏了我以前的代码,所以如果不继续前进,请反对

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    Unity 的 Input.GetButtonUp 和 Input.GetButtonDown 处理您在输入设置中设置的“虚拟”按钮。 Input.GetKeyUp/Input.GetKeyDown 是关于键盘上的键。因此,您应该选择 GetKey 或 GetButton,但不能同时选择两者。

    正如我所见,您希望您的对象在用户按键的所有时间都旋转。我建议您在课堂上使用附加的“状态”属性:

    private State state = State.IDLE;
    private enum State {
      LEFT, RIGHT, IDLE
    };
    

    更新您的代码:

    if (Input.GetKeyDown(KeyCode.D)) {
      state = State.RIGHT;
    }
    if (Input.GetKeyDown(KeyCode.A)) {
      state = State.LEFT;
    }
    if (Input.GetKeyUp(KeyCode.D) || Input.GetKeyUp(KeyCode.A)) {
      state = State.IDLE;
    }
    switch (state) {
      case State.LEFT:
        rd.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        rd.transform.eulerAngles = new Vector3(0, 10, 0);
      break;
      case State.RIGHT:
        rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        rd.transform.eulerAngles = new Vector3(0, -10 , 0);
      break;
      case State.IDLE:
        rd.transform.eulerAngles = Vector3.zero;
      break;
    }
    

    几个建议:

    1. 在 FixedUpdate() 方法而不是 Update() 中使用物理操作
    2. 对键盘按键使用 Unity 的 KeyCode 枚举
    3. 保持代码干净
    4. 先开发算法,然后将该算法转换为代码

    【讨论】:

      【解决方案2】:

      当我替换你的

      Input.GetButtonUp("a")
      

      Input.GetKeyUp("a")
      

      这完全没问题。

      您是否尝试自己调试此代码?因为通过在这一行设置断点很容易找出Input.GetButtonUp(…)没有被调用。

      顺便说一句。我会考虑像这样编写您的输入代码:

      if (Input.GetKey("d"))
      {
          rd.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
          rd.transform.eulerAngles = new Vector3(0, 10, 0);
      }
      else if (Input.GetKey("a"))
      {
          rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
          rd.transform.eulerAngles = new Vector3(0, -10, 0);
      }
      else
      {
          rd.transform.eulerAngles = new Vector3(0, 0, 0);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多