1

我目前正在使用电影机制作第三人称相机。我的球员的动作很有效,我希望他看向他正在移动的方向,但要考虑到摄像机的旋转。当我在移动播放器的同时不移动相机时它可以工作,但是当我移动相机时,我的播放器的旋转是滞后的,而且我的相机的每次移动似乎也是滞后的。对不起我的英语我希望很清楚这是我的代码:

public class ThirdPersonScript : MonoBehaviour
 
 {
     [SerializeField] private float speed;
     [SerializeField] private float jumpForce;
     [SerializeField] private Transform feet;
     [SerializeField] private LayerMask floorMask;
     [SerializeField] private Transform cam;
 
     private Vector3 direction;
     private Rigidbody rb;
     private bool canJump;
 
     // Start is called before the first frame update
     void Start()
     {
         rb = GetComponent<Rigidbody>();
     }
 
     // Update is called once per frame
     void Update()
     {
         
         direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
         direction = Quaternion.AngleAxis(cam.rotation.eulerAngles.y, Vector3.up) * direction;
 
         if (direction.magnitude > 1.0f)
         {
             direction = direction.normalized;
         }
 
         direction *= speed;
 
         canJump = Input.GetKeyDown(KeyCode.Space) ? true : false;
     }
 
     void FixedUpdate()
     {
       
         if (Physics.CheckSphere(feet.position, 0.1f, floorMask))
         {            
             if (canJump)
                 rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
             else    
                 rb.velocity = new Vector3(direction.x, 0, direction.z);
         }
         else          
             rb.velocity = new Vector3(direction.x, rb.velocity.y, direction.z);
    
         if (direction != Vector3.zero)
         {
             Quaternion targetRotation = Quaternion.LookRotation(direction);
             targetRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 1080*Time.fixedDeltaTime);
             rb.MoveRotation(targetRotation);
 
         }
     }
 }

以及我的电影机设置和层次结构的屏幕截图: 在此处输入图像描述

4

1 回答 1

1

尝试更改LateUpdate() 中的方向,而不是 Update() :

 void LateUpdate()
 {
     
     direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
     direction = Quaternion.AngleAxis(cam.rotation.eulerAngles.y, Vector3.up) * direction;

     if (direction.magnitude > 1.0f)
     {
         direction = direction.normalized;
     }

     direction *= speed;

     canJump = Input.GetKeyDown(KeyCode.Space) ? true : false;
 }

在调用所有更新函数之后调用 LateUpdate。这对于命令脚本执行很有用。例如,跟随相机应始终在 LateUpdate 中实现,因为它跟踪可能已在 Update 中移动的对象。 https://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html

于 2021-10-27T03:34:24.727 回答