In the development of Unity3D, we often encounter a variety of camera perspectives. When we control the movement of characters, we also need the camera to move or transform according to certain rules. In the following articles, you will see an understanding of each camera transformation to be implemented and the code to implement it.

Let’s first take a look at the most commonly used fixed following perspective

This fixed following perspective is relatively simple and can be implemented in a variety of ways, two of which are mainly introduced here.

1. You only need to place the Camera object on the follow model as a child object, without any coding.



Of course, this approach is extremely low scalability and is not recommended, and inevitably complicates the process when you need to destroy the model.

2. The second method uses offsets to perform operations

The code that controls Camera movement by hanging a move. cs script under the Camera object is easy to understand: use public variables to bind the actor object in the ISnpector interface. The offset is obtained in the Awake method as a fixed difference between the camera and the role. Then just add a fixed difference in LateUpdate to the current camera position based on the current character coordinates. A good way to do this is to place camera shifts in lateUpdates. Updates are very variable frame by frame, there is no fixed sequence of script updates. Lateupdates are called after all update calls. Can be used to adjust the script execution order.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveCamera : MonoBehaviour
{
    public Transform player;

    private Vector3 offset;

    private void Awake()
    {
        offset = transform.position - player.position;
    }

    private void LateUpdate(){ transform.position = player.position + offset; }}Copy the code