【问题标题】:How can I prevent this from looping?我怎样才能防止这个循环?
【发布时间】:2019-02-22 21:18:18
【问题描述】:

我有一个按钮,我按下它可以跳跃。我现在的问题是一旦我按下这个按钮,我的播放器就会一直跳下去。但是我想做到这一点,一旦我落地,我就必须再次按下跳跃按钮。这是我当前的代码:

  public void onButtonJump()
    {
         if (controller.isGrounded )
        {

            verticalVelocity = -gravity * Time.deltaTime;

            {

                verticalVelocity = jumpForce;
                animator.SetBool("is_in_air", true);
                jump.Play();


            }

        }
        else
        {
            animator.SetBool("is_in_air", false);
            verticalVelocity -= gravity * Time.deltaTime;
        }
    }

如何防止这种情况循环播放,以便在接地后再次按下按钮?

【问题讨论】:

  • 你在哪里调用 onButtonJump() ,需要更多代码。
  • controller.isGrounded 设置在哪里?
  • onButtonJump() 在我单击游戏中的画布 ui 按钮时被调用,因此它位于 onClick() 上,controller.isgrounded 检查我是否在游戏中。它的那部分工作它可以告诉我是否在我的游戏的底层。控制器在我的播放器上。
  • 愚蠢的问题:为什么不直接在设置animator.SetBool("is_in_air", true); 的同一点上明确设置IsGrounded = false - 我有一种很好的感觉,可以为你解决它......你有两个不同的布尔值似乎代表相同的概念,但表示相反:IsGroundedis_in_air) -- 请注意,这种类型的构造看起来很简单,但很容易变得非常混乱。
  • 这不是大卫的意思。他说您应该使用controller.isGrounded 并将其与动画一起设置为false。你只是检查它,你从来没有设置它。

标签: c# unity3d


【解决方案1】:

不要在按钮下做“重力”,只能在 FixedUpdate(“物理框架”更新)中做:

void FixedUpdate() {
    if ( controller.isGrounded )
        verticalVelocity = 0;
    else
        verticalVelocity -= gravity * Time.deltaTime;

    // Apply velocity to transform here
}

void onButtonJump() {
    if (controller.isGrounded ) {
        verticalVelocity = jumpVelocity;
        // Play animation and sound here
    }
}

【讨论】: