Unity implements 2D game following camera (smooth movement)

running result

The camera operation effect is as follows.
Insert image description here

player character

First create an available player character and write the movement logic. If you want to use the resources purchased in the Unity store, you can click the Window menu bar > Package Manager option to open the Package Manager window, as shown below, and then download the resources you need. .
Insert image description here
Insert image description here

Script

Create a new script named FollowCamera, and then mount the script to the Camera.
Insert image description here

Field

The following camera we want to create has the function of smooth movement, so we need to create two fields, one field to represent the following object, and one field to represent the smoothness of the camera movement.
Declare a Transform class variable target, which is used to specify the target object to be followed by the camera. Note that it must be declared public so that we can assign the target object to the variable in the editor.
Declare a float type variable damping, which is used to specify the smoothness of the following. The larger the value, the smoother the following. The default value is 1.

public Transform target; // 跟随的目标物体
public float damping = 1; // 跟随的平滑程度

follow logic

We implement the following logic code in the LateUpdate() method, which is called at the end of each frame.

private void LateUpdate()
{
    
    
}

In the LateUpdate() method, first determine whether the target object exists (whether it has been assigned to the target variable). If there is no target object, no operation is performed to avoid reporting an error.

if (target != null)
{
    
    
}

Next calculate the vector by which the camera should move:

// 计算目标位置在屏幕上的坐标
Vector3 targetPosition = Camera.main.WorldToViewportPoint(target.position);
// 计算摄像机应该移动的向量
Vector3 delta = target.position - Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, targetPosition.z));

First, use the Camera.main.WorldToViewportPoint() method to convert the target object's position into viewport coordinates (relative to the camera's screen view scale).
Then, by calculating the delta vector, the offset between the center position of the target object in the viewport coordinate system and the center position of the screen is obtained. Use the Camera.main.ViewportToWorldPoint() method to convert the offset to an offset in the world coordinate system.

Next calculate the target position and move the camera.

// 计算摄像机的目标位置
Vector3 destination = transform.position + delta;
// 使用平滑阻尼移动摄像机
transform.position = Vector3.Lerp(transform.position, destination, damping * Time.deltaTime);

Based on the calculated target position of the camera, use the Vector3.Lerp() method to move the camera to the target position in a smooth damping manner.

The script is now written. It can make the camera follow the target object smoothly and keep the target object in the center of the camera. By adjusting the value of the damping variable, we can also control the smoothness of the following.

Complete code

using UnityEngine;

public class FollowCamera: MonoBehaviour
{
    
    
    public Transform target; // 跟随的目标物体
    public float damping = 1; // 跟随的平滑程度

    private void LateUpdate()
    {
    
    
        if (target != null)
        {
    
    
            // 计算目标位置在屏幕上的坐标
            Vector3 targetPosition = Camera.main.WorldToViewportPoint(target.position);
            // 计算摄像机应该移动的向量
            Vector3 delta = target.position - Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, targetPosition.z));
            // 计算摄像机的目标位置
            Vector3 destination = transform.position + delta;
            // 使用平滑阻尼移动摄像机
            transform.position = Vector3.Lerp(transform.position, destination, damping * Time.deltaTime);
        }
    }
}

Other related article links

Unity2D implements an enemy character that moves left and right.
Unity creates a movable 2D character.

Guess you like

Origin blog.csdn.net/weixin_44499065/article/details/132800361