using UnityEngine;
public enum CameraType
{
TopDown,
Platformer2D,
Game3D
}
public class CameraFollow : MonoBehaviour
{
public CameraType cameraType;
public Transform target;
public Vector3 offset;
public float smoothSpeed = 0.125f;
private void LateUpdate()
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
if (cameraType == CameraType.TopDown)
{
smoothedPosition.y = transform.position.y;
}
else if (cameraType == CameraType.Platformer2D)
{
smoothedPosition.z = transform.position.z;
}
transform.position = smoothedPosition;
}
}
In this script, we define the CameraType
enum at the top of the file, which has three options: TopDown
, Platformer2D
, and Game3D
. Then, we define a public cameraType
variable of type CameraType
that can be set in the Unity editor.
The target
variable represents the object that the camera will follow, and offset
represents the distance between the camera and the target. smoothSpeed
is used to control how smoothly the camera follows the target.
In the LateUpdate()
method, we calculate the desired position of the camera based on the target’s position and the offset, and then use Vector3.Lerp()
to smoothly move the camera towards the desired position.
Finally, we check the value of cameraType
and adjust the camera’s position accordingly. If the camera type is TopDown
, we keep the camera’s y position the same as its current position. If the camera type is Platformer2D
, we keep the camera’s z position the same as its current position. Otherwise, we leave the camera’s position unchanged.