I have a script that controls what the bounds of an Orthographic camera are, somewhat loosely based on shieldgenerator7’s answer here, from this thread: https://answers.unity.com/questions/433665/need-help-with-2d-orthographic-camera-zooming.htm
It works ALMOST perfectly. However… when it hits widescreen layouts, it’s got severe jitter issues. It has a tendency to flip back and forth, and never stay in one place after screen sizes past 16:x are tried. The camera itself is rotated slightly by 10 on x, however this otherwise works perfectly for 3:2, 4:3, and 5:4.
Is there any good way to handle widescreen sizes with camera bounding boxes? The script I have so far is below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Camera screenCamera;
public GameObject boundsMarker;
public Bounds visibleBounds;
public Transform playerTarget;
[SerializeField]
float boundingBoxPadding = 2f;
[SerializeField]
float minimumOrthographicSize = 5f;
[SerializeField]
float zoomSpeed = 20f;
Vector2 cameraSizeWorld;
Vector2 halfSize;
private void Awake()
{
screenCamera = GetComponent<Camera>();
}
// Start is called before the first frame update
void Start()
{
playerTarget = WorldController.Instance.cameraTarget;
Vector3 tPos = playerTarget.position;
tPos.z = -20;
transform.position = tPos;
}
private void FixedUpdate()
{
// In case the box gets updated during play //
visibleBounds = boundsMarker.GetComponent<BoxCollider>().bounds;
if (playerTarget != null)
{
Vector3 tPos = playerTarget.position;
tPos.z = -20;
transform.position = tPos;
updateExtents();
}
}
private void updateExtents()
{
cameraSizeWorld = Camera.main.ViewportToWorldPoint(Vector2.one) - Camera.main.ViewportToWorldPoint(Vector2.zero);
halfSize = cameraSizeWorld / 2;
}
private void LateUpdate()
{
Vector3 v3 = transform.position;
v3.x = Mathf.Clamp(v3.x, visibleBounds.min.x + halfSize.x, visibleBounds.max.x - halfSize.x);
v3.y = Mathf.Clamp(v3.y, visibleBounds.min.y + halfSize.y, visibleBounds.max.y - halfSize.y);
transform.position = v3;
}
}