lock camera boundaries when pinch-zoomed
Hi all, this is my first game and i'm making a 2d board game. i found a script for a (clash of clans's type) pinch zoom. and another script for finding the boundaries of camera. now i can't figure how to lock the camera so that when you move around you don't go off map!
using UnityEngine;
public class PinchZoom : MonoBehaviour
{
public float moveSensitivityX = 1.0f;
public float moveSensitivityY = 1.0f;
public bool updateZoomSensitivity = true;
public float orthoZoomSpeed = 0.05f;
public float minZoom = 1.0f;
public float maxZoom = 20.0f;
public bool invertMoveX = false;
public bool invertMoveY = false;
float positionY = 0;
float positionX = 0;
//float tempY = 0;
private Camera _camera;
void Start(){
_camera = Camera.main;
}
void Update()
{
float screenAspect = (float)Screen.width / (float)Screen.height;
float cameraHeight = _camera.orthographicSize * 2;
Bounds bounds = new Bounds(
_camera.transform.position,
new Vector3(cameraHeight * screenAspect, cameraHeight, 0));
//Debug.Log (bounds.max);
if (updateZoomSensitivity) {
moveSensitivityX = _camera.orthographicSize / 5.0f;
moveSensitivityY = _camera.orthographicSize / 5.0f;
}
Touch[] touches = Input.touches;
if (touches.Length > 0) {
//Single Touch(move)
if(touches.Length == 1){
if(touches[0].phase == TouchPhase.Moved){
Vector2 delta = touches[0].deltaPosition;
positionX = delta.x * moveSensitivityX * Time.deltaTime;
positionX = invertMoveX ? positionX : positionX * -1;
//if(bounds.max.y < 703){
positionY = delta.y * moveSensitivityY * Time.deltaTime;
positionY = invertMoveY ? positionY : positionY * -1;
_camera.transform.position += new Vector3 (positionX,positionY,0);
}
}
//double touch(zoom)
if(touches.Length == 2){
Touch touchOne = touches[0];
Touch touchTwo = touches[1];
Vector2 touchOnePreviousPosition = touchOne.position - touchOne.deltaPosition;
Vector2 touchTwoPreviousPosition = touchTwo.position - touchTwo.deltaPosition;
float prevTouchDeltaMag = (touchOnePreviousPosition - touchTwoPreviousPosition).magnitude;
float touchDeltaMag = (touchOne.position - touchTwo.position).magnitude;
float deltaMagDiff = prevTouchDeltaMag - touchDeltaMag;
_camera.orthographicSize += deltaMagDiff * orthoZoomSpeed;
_camera.orthographicSize = Mathf.Clamp(_camera.orthographicSize, minZoom, maxZoom);
}
}
}
}
Comment