【问题标题】:Gravity not affecting Player when jumping跳跃时重力不影响玩家
【发布时间】:2019-02-01 05:46:43
【问题描述】:

我有一个 Endless Runner 玩家,它在任何状态下都可以跳跃。按空格键时,我的播放器会无限上天。

它有动画和角色控制器,但没有Rigidbody。我在脚本中使用了它。

在动画师中,我添加了一个bool ground 和一个跳跃触发器。

我将条件grounded设置为真,从任何状态转换到跳转。

:Screenshot

下面是代码

private CharacterController controller;
private float jumpForce = 4.0f;
private float gravity = 12.0f;
private float verticalVelocity;

void Update()
{
    Vector3 moveVector = Vector3.zero;
    moveVector.x = (targetPosition - transform.position).normalized.x * speed;

    bool isGrounded = IsGrounded();
    animator.SetBool("jumping", isGrounded);

    //Calculate Y
    if (isGrounded) //if grounded
    {
        verticalVelocity = -0.1f;

        if(Input.GetKeyDown(KeyCode.Space))
        {
            //jump
            animator.SetTrigger("jumping");
            verticalVelocity = jumpForce; 
        }
        else
        {
            verticalVelocity -= (gravity * Time.deltaTime);

            //fast faling mechanic
            if(Input.GetKeyDown(KeyCode.Space))
            {
                verticalVelocity = -jumpForce;
            }
        }
    }
}

private bool IsGrounded()
{
    Ray groundRay = new Ray(new Vector3(
        controller.bounds.center.x,
        (controller.bounds.center.y - controller.bounds.extents.y) + 0.2f,
        controller.bounds.center.z),
        Vector3.down);
    return (Physics.Raycast(groundRay, 0.2f + 0.1f));

}

非常感谢任何想法!

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    如果您希望 Unity 系统处理您的 physics,您将不得不在那里使用 Rigidbody 组件。

    否则,您需要模拟加速度。通过增加FixedUpdate中每个物理滴答的速度来做到这一点

    float gravityVelocity = 0f;
    
    float gravityFactor = 0.5f;
    float gravityAcceleration = 9.2f * gravityFactor;
    
    void FixedUpdate()
    {
        gravityVelocity += gravityAcceleration * Time.fixedDeltaTime;
    
        gameObjectToUpdate.transform.position +=
            new Vector3(0, gameObjectToUpdate.transform.position.y - gravityVelocity, 0);
    }
    

    【讨论】:

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