微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 CineMachine 的第三人称刚体运动脚本

如何解决使用 CineMachine 的第三人称刚体运动脚本

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

    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,0f) * Vector3.forward;

        rb.veLocity = moveDir.normalized * speed;
    }

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

解决方法

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

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。