Code for simple Unity3D camera following main character:

Create a script file CameraFollow in Unity3D software, and open the script file, use the following code:

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform target; // 跟随的目标,即主角
    public float smoothSpeed = 0.125f; // 摄像机跟随的速度
    public Vector3 offset; // 摄像机与主角之间的距离

    void LateUpdate()
    {
        Vector3 desiredPosition = target.position + offset; // 计算摄像机应该移动到的位置
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed); // 平滑移动摄像机
        transform.position = smoothedPosition; // 更新摄像机的位置
    }
}

There are three public variables in this script:

  1. target: The target to follow, that is, the protagonist, needs to be set manually in the Inspector panel.
  2. smoothSpeed: The speed at which the camera follows, used to control the smoothness of the camera movement.
  3. offset: The distance between the camera and the protagonist, which also needs to be set manually.

In the LateUpdate() function, first calculate the position where the camera should move, and then use the Lerp function to move the camera smoothly and update the position of the camera. Since the LateUpdate() function is executed after the Update() function, it can ensure that the camera moves after the main character moves to avoid the situation of freezing.

 

Mount this code on the camera, and then assign the Transform component of the protagonist to the target variable. If you need to adjust the distance between the camera and the protagonist, you can modify the value of the offset variable.

Guess you like

Origin blog.csdn.net/WMcsdn11124/article/details/130306673