I am trying to make a camera system for a 2D platformer, with three camera modes to begin with:
Follow, normally following the player
Horizontal: Y is set, X follows player
Static: Locked to a certain position in the world
When I switch between modes, the camera snaps to the new location immediately. I want it to pan as seen in games like Hollow Knight.
This is my code:
using UnityEngine;
public class CameraFollowObject : MonoBehaviour
{
public CamMode mode { get; set; }
public Vector2 position { get; set; }
[Header("References")]
[SerializeField] private Transform playerTransform;
[Header("Flip Rotation Stats")]
[SerializeField] private float flipVRotationTime = 0.5f;
private Player player;
private bool isFacingRight;
private void Start()
{
transform.position = player.transform.position;
enabled = true;
player = playerTransform.gameObject.GetComponent<Player>();
isFacingRight = player.motor.facingRight;
}
public void UpdateCamera()
{
Vector2 target = mode switch
{
CamMode.Horizontal => new Vector2(player.transform.position.x, position.y),
CamMode.Static => position,
_ => player.transform.position
};
transform.position = target;
}
public void CallTurn()
{
LeanTween.rotateY(gameObject, DetermineEndRotation(), flipVRotationTime).setEaseInOutSine();
}
private float DetermineEndRotation()
{
isFacingRight = !isFacingRight;
if (isFacingRight)
{
return 0f;
}
else
{
return 180f;
}
}
}
Camera Follow Object follows the player and rotates on player flip to smoothly pan from left bias to right bias.
using System.Collections;
using UnityEngine;
using Cinemachine;
public class CameraManager : MonoBehaviour
{
public static CameraManager instance;
private CamMode currentMode;
[SerializeField] private CameraFollowObject followObject;
public bool isLerpingYDamping { get; private set; }
public bool lerpedFromPlayerFalling { get; set; }
private void Awake()
{
if (instance == null)
{
instance = this;
}
}
public void SwapCamera(CamMode left, CamMode right, Vector2 exitDir, Vector2 pos)
{
if (currentMode == left && exitDir.x > 0f)
{
followObject.position = pos;
currentMode = followObject.mode = right;
return;
}
if (currentMode == right && exitDir.x < 0f)
{
followObject.position = pos;
currentMode = followObject.mode = left;
return;
}
}
}
Camera Manager to switch Cameras
The Cameras are switched by triggers, it all works perfectly fine, only thing is, that the camera instantly snaps. I tried changing the transform.position = target; to lerp between current and target, but that just made the camera fall behind when walking.
