0

我正在尝试使用 Cinemachine 作为相机创建一个第三人称动作脚本,我遵循了 Brackeys“Unity 中的第三人称动作”YouTube 教程。然后我将它的基础从角色控制器更改为刚体,运动效果非常好。然而,当我移动与重力作斗争的玩家时,我的代码将刚体 y 轴的速度设置为 0,从而使玩家在我移动时缓慢地抖动到地面。然而,当玩家停止移动时,角色确实会掉到地上。我所需要的只是让脚本忽略 y 轴并简单地听取统一的重力。

    void Update()
{
    if (!photonView.isMine)
    {
        Destroy(GetComponentInChildren<Camera>().gameObject);
        Destroy(GetComponentInChildren<Cinemachine.CinemachineFreeLook>().gameObject);
        return;
    }

    float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");

    isGrounded = Physics.CheckSphere(new Vector3(transform.position.x, transform.position.y - 1, transform.position.z), 0.01f, layerMask);

    Vector3 inputVector = new Vector3(horizontal, 0f, vertical).normalized;

    if (inputVector.magnitude >= 0.1f)
    {
        float targetAngle = Mathf.Atan2(inputVector.x, inputVector.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
        float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
        transform.rotation = Quaternion.Euler(0f, angle, 0f);

        Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;

        rb.velocity = moveDir.normalized * speed;
    }

    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        rb.AddForce(Vector3.up * jumpForce);
    }
}
4

1 回答 1

0

玩家抖动的原因是,在您的移动部分,您将 y 速度设置为 0,因为Vector3.forward返回new Vector3(0, 0, 1)并且您仅围绕 y 轴旋转矢量。取而代之的是,考虑这样做:

Vector3 moveDir = new Vector3(transform.forward.x, rb.velocity.y, transform.forward.z);

这将保持原来的速度,消除抖动。

注意:transform.forward自动获取玩家的前向向量。

于 2021-03-23T22:51:32.950 回答