You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
103 lines
2.7 KiB
103 lines
2.7 KiB
using UnityEngine; |
|
using UnityEngine.EventSystems; |
|
|
|
public class DragCamera2D : MonoBehaviour |
|
{ |
|
public Camera cam; |
|
|
|
[Header("Panning")] |
|
public bool panningEnabled = true; |
|
[Range(-5, 5)] |
|
public float panSpeed = -0.06f; |
|
public bool keyboardInput = false; |
|
public bool inverseKeyboard = false; |
|
|
|
[Header("Zoom")] |
|
public bool zoomEnabled = true; |
|
public bool linkedZoomDrag = true; |
|
public float maxZoom = 10; |
|
[Range(0.01f, 10)] |
|
public float minZoom = 0.5f; |
|
[Range(0.1f, 10f)] |
|
public float zoomStepSize = 0.5f; |
|
|
|
void Start() { |
|
if (cam == null) { |
|
cam = Camera.main; |
|
} |
|
} |
|
|
|
void Update() { |
|
if (panningEnabled) { |
|
panControl(); |
|
} |
|
|
|
if (zoomEnabled) { |
|
zoomControl(); |
|
} |
|
} |
|
|
|
//click and drag |
|
public void panControl() { |
|
// if mouse is down |
|
if (Input.GetMouseButton(2)) { |
|
if (!EventSystem.current.IsPointerOverGameObject()) |
|
{ |
|
float x = Input.GetAxis("Mouse X") * panSpeed; |
|
float y = Input.GetAxis("Mouse Y") * panSpeed; |
|
|
|
if (linkedZoomDrag) |
|
{ |
|
x *= Camera.main.orthographicSize; |
|
y *= Camera.main.orthographicSize; |
|
} |
|
|
|
transform.Translate(x, y, 0); |
|
|
|
} |
|
|
|
} |
|
|
|
// if keyboard input is allowed |
|
if (keyboardInput) { |
|
float x = -Input.GetAxis("Horizontal") * panSpeed; |
|
float y = -Input.GetAxis("Vertical") * panSpeed; |
|
|
|
if (linkedZoomDrag) { |
|
x *= Camera.main.orthographicSize; |
|
y *= Camera.main.orthographicSize; |
|
} |
|
|
|
if (inverseKeyboard) { |
|
x = -x; |
|
y = -y; |
|
} |
|
transform.Translate(x, y, 0); |
|
} |
|
} |
|
|
|
// managae zooming |
|
public void zoomControl() |
|
{ |
|
if (!EventSystem.current.IsPointerOverGameObject()) |
|
{ |
|
if ((Input.GetAxis("Mouse ScrollWheel") > 0) && Camera.main.orthographicSize > minZoom) // forward |
|
{ |
|
Camera.main.orthographicSize = Camera.main.orthographicSize - zoomStepSize; |
|
|
|
// Keep soze above 0 or error. |
|
if (Camera.main.orthographicSize < 0.01f) |
|
{ |
|
Camera.main.orthographicSize = 0.01f; |
|
} |
|
} |
|
|
|
if ((Input.GetAxis("Mouse ScrollWheel") < 0) && Camera.main.orthographicSize < maxZoom) // back |
|
{ |
|
Camera.main.orthographicSize = Camera.main.orthographicSize + zoomStepSize; |
|
} |
|
} |
|
|
|
} |
|
|
|
}
|
|
|