【Unity踩坑记录】使用Rigidbody模拟跳跃时,刚体会突然上升

最初的写法

private void FixedUpdate()
{
    if (!isGrounded)
    {
        return;
    }

    float rawHorizontal = Input.GetAxis("Horizontal");
    float rawVertical = Input.GetAxis("Vertical");

    Vector3 localDirection = new(rawHorizontal, 0, rawVertical);
    Vector3 worldDirection = transform.TransformDirection(localDirection);
    Vector3 moveVelocity = worldDirection * moveSpeed;

    if (jumpTriggered)
    {
        jumpTriggered = false;
        moveVelocity.y = jumpVelocity;
    }

    rigidbody.velocity = moveVelocity;
}

经过不断地调试发现,标题所述问题是因为,当jumpTriggered为False,即没有按下跳跃键时,rigidbody的velocity.y被设置为了0,也就是说在跳跃后的一瞬间,velocity就被强制归零了,因此只要加下面这样一条即可。

    if (jumpTriggered)
    {
        jumpTriggered = false;
        moveVelocity.y = jumpVelocity;
    }
    else
    {
        moveVelocity.y = rigidbody.velocity.y;
    }
posted @ 2024-08-30 14:53  Re-Ch  阅读(90)  评论(0)    收藏  举报