How to move/lock camera upon checkpoint?
Hello, I'm making a game that would require an animation trigger to play before the camera is unlocked to follow the player to its right where the camera would lock again. (Similar to old, arcade fighting games)
I'm pretty new to programming and the code I have now for the CameraController was from a tutorial that continuously follows the player only along the x-axis.
//camera controller that only follows player on x-axis
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
//how far player can move away from camera before it follows
public float xCharRange = 1.0f;
//smoothing of camera movement
public float xTrackSmooth = 10.0f;
//boundaries our camera can move in X Axis
public Vector2 maxXLevel;
public Vector2 minXLevel;
//hold our camera track point transform
public Transform cameraTrackPoint;
// Update is called once per frame
void FixedUpdate ()
{
TrackPlayer ();
}
//getting distance out character is away from camera if we went past the set range
//we will allow
bool CheckXCharRange ()
{
return Mathf.Abs (transform.position.x - cameraTrackPoint.position.x) > (xCharRange);
}
//camera tracking main action
void TrackPlayer ()
{
//variable to store the positional information of our player camera
float targetX = transform.position.x;
//if character is out of range, then move camera to follow character until in range again
if (CheckXCharRange ())
{
targetX = Mathf.Lerp (transform.position.x, cameraTrackPoint.position.x, xTrackSmooth * Time.deltaTime);
}
//clamp our camera's range of movement
targetX = Mathf.Clamp (targetX, minXLevel.x, maxXLevel.x);
//move our camera after all calculations are done with above...
transform.position = new Vector3(targetX, transform.position.y, transform.position.z);
}
}
Answer by FortisVenaliter · Jan 27, 2016 at 06:27 PM
There are a number of ways to do this, but I'll describe my favorite here:
I usually have a GameSession class that manages global variables, including the main camera. It also has a field for an 'event' camera. Whenever that field is set with an active camera, it disables the normal main one.
So, for your game, whenever you get to the checkpoint, you'd just instantiate a camera with whatever locking scripts you want, and set it in that event camera field. Then the session would notice it is set, and disable the main camera. When you are done with the locking, just delete the camera and clear the field, and the main camera will be reactivated. It takes a bit of coding, but it works well, in my experience.
Your answer