Question by
dovster1 · Feb 26, 2019 at 02:26 AM ·
cameracamera-movementcamera.main
Fix Camera Moving Out Of Screen
Hi, so I am relatively new to unity. I have a camera in my game that I pieced together from online tutorials. It can zoom in/out and pan around. The problem is it pans around outside of the image. For now, it snaps back in place once it is outside of the image. But, I don't want it to even go beyond the image. I need it clamped like a Scroll Rect. The code is included below. Thanks!
C#
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PanZoom : MonoBehaviour { public BoxCollider2D Bounds; private Vector3 _min, _max; private Vector2 x, y;
Vector3 touchStart;
public float zoomOutMin = 1;
public float zoomOutMax = 8;
//GO stands for GameObject
public GameObject CameraGO;
public GameObject CanvasGO;
public void Start()
{
_min = Bounds.bounds.min;
_max = Bounds.bounds.max;
}
// Update is called once per frame
void Update()
{
var cameraHalfWidth = Camera.main.orthographicSize * ((float)Screen.width / Screen.height);
var x = transform.position.x;
var y = transform.position.y;
x = Mathf.Clamp(x, _min.x + cameraHalfWidth, _max.x - cameraHalfWidth);
y = Mathf.Clamp(y, _min.y + Camera.main.orthographicSize, _max.y - Camera.main.orthographicSize);
transform.position = new Vector3(x, y, transform.position.z);
if (Input.GetMouseButtonDown(0))
{
touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.touchCount == 2)
{
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
float prevMagnitude = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float currentMagnitude = (touchZero.position - touchOne.position).magnitude;
float difference = currentMagnitude - prevMagnitude;
zoom(difference * 0.01f);
}
else if (Input.GetMouseButton(0))
{
Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
Camera.main.transform.position += direction;
}
zoom(Input.GetAxis("Mouse ScrollWheel"));
}
void zoom(float increment)
{
float multiplier = 1000f;
Camera.main.orthographicSize = Mathf.Clamp(Camera.main.orthographicSize - increment * multiplier, zoomOutMin, zoomOutMax);
}
}
Comment