Unity objects always face the direction of the camera

using UnityEngine;

public class LookAtCamera : MonoBehaviour
{
    private Transform cameraTransform;
    public float rotationSpeed = 10f;

    void Start()
    {
        cameraTransform = Camera.main.transform; // 获取主摄像机的Transform组件
    }

    void Update()
    {
        Vector3 direction = cameraTransform.position - transform.position;
        direction.y = 0f; // 只在x-z平面上旋转
        Quaternion targetRotation = Quaternion.LookRotation(direction, Vector3.up);
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
    }
}

In the above code, a cameraTransform variable is first defined to store the Transform component of the camera.

Use Camera.mainthe method to get the main camera in the scene, then get its Transform component and assign it to cameraTransforma variable.

Then, in the Update method, we calculate the vector difference between the camera position and the object position and store it in the direction variable. Since we only want to rotate the object in the xz plane, we set the y component of the direction vector to 0.

Next, we call the Quaternion.LookRotation function and pass it the direction vector and the up vector (Vector3.up) as parameters to get the rotation of the Quaternion so that the object faces the camera. Then, we use the Quaternion.Slerp function to smoothly transition the rotation angle of the object to the target angle. We also use the rotationSpeed ​​variable to control the rotation speed.

Finally, just attach the above script to the object that needs to always face the camera and rotate around the y-axis.

Guess you like

Origin blog.csdn.net/qq_51245392/article/details/130559723