Real quick. I’m making a 2D game where my player is moving downwards along the Y-axis. Nothing brings the player back up so I would like to lock my camera on the player. When my player jumps, the camera follows which is basically what i’m trying to prevent but I cant seem to find an “easy” solution for this. Thanks in advance if anyone can help me out!
[RequireComponent(typeof(Camera))]
public class CameraFollow : MonoBehaviour
{ #region Public Variables
//Value : Default Target of the camera when the game started
public Transform defaultTargetReference;
public Vector3 cameraOffSet = Vector3.one;
[Range(0f, 1f)]
public float cameraFollowingVelocity = 0.1f;
#endregion
#region Private Variables
private Transform m_TransformReference;
//Value : The current target of the camera will always be stored in this variable, as we can change it through the runtime.
private Transform m_CurrentTargetOfCamera;
private Vector3 m_ModifiedPosition;
#endregion
#region Mono Behaviour
private void Awake()
{
m_TransformReference = transform;
//Initially, the current target of the camera is our default target which we set from the editor
m_CurrentTargetOfCamera = defaultTargetReference;
}
private void LateUpdate()
{
//if : The current target of the camera is destroyed (Which you changed by calling the "ChangeCameraTarget()"), it will get back to its default target
if (m_CurrentTargetOfCamera == null)
m_CurrentTargetOfCamera = defaultTargetReference;
//Calculating : Finding the new position of the camera considering the offset. for your case, I believe the offset would be (0,0,-10)
//*************
if (m_TransformReference.position.y > (m_CurrentTargetOfCamera.position.y + cameraOffSet.y))
{
m_ModifiedPosition = Vector3.Lerp(
m_TransformReference.position,
m_CurrentTargetOfCamera.position + cameraOffSet,
cameraFollowingVelocity
);
//Assigning : the changed position
m_TransformReference.position = m_ModifiedPosition;
}
}
#endregion
#region Public Callback
/// <summary>
/// Use this function to change the camera target in runtime.
/// </summary>
/// <param name="t_CameraTarget"></param>
public void ChangeCameraTarget(Transform t_CameraTarget)
{
m_CurrentTargetOfCamera = t_CameraTarget;
}
#endregion