Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
a script for orthogonal cameras, which starts moving the camera when the player is about to leave the visible region. can be seen here: https://gfycat.com/NecessaryFelineHare
using UnityEngine;
public class SomeCameraTest : MonoBehaviour {
private Bounds outer_bounds;
private Bounds inner_bounds;
private bool bounds_reached = false;
[SerializeField] private Transform target;
[SerializeField] private Camera cam;
[SerializeField] private float camSpeed = 8f; // set to player speed
[SerializeField] private Vector2 innerBoundsOffset = new Vector2(3, 3);
private Vector3 velocity;
void Start() {
outer_bounds = new Bounds(new Vector3(0, 0, 0), new Vector3(2*cam.orthographicSize * cam.aspect, 10, 2*cam.orthographicSize));
outer_bounds.Expand(new Vector3(-1, 0, -1)); // seems to be nicer, maybe even -2.
inner_bounds = outer_bounds;
inner_bounds.Expand(new Vector3(-2*innerBoundsOffset.x, 0, -2*innerBoundsOffset.y));
}
void Update() {
var displacement = target.position - transform.position;
if (inner_bounds.Contains(displacement)) {
bounds_reached = false;
} else {
if(! outer_bounds.Contains(displacement)) {
bounds_reached = true;
}
}
if (bounds_reached) {
var dir = (displacement - inner_bounds.ClosestPoint(displacement)).normalized;
var point = Vector3.Dot(dir, displacement)*dir;
// choose 1 of the two:
transform.position = Vector3.MoveTowards(transform.position, transform.position + point, camSpeed*Time.deltaTime);
// transform.position = Vector3.SmoothDamp(transform.position, transform.position + point*2, ref velocity, 0.5f);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment