122 lines
3.3 KiB
C#
122 lines
3.3 KiB
C#
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
|
|
public class CameraHandler : MonoBehaviour
|
|
{
|
|
bool isDragging = false;
|
|
Vector2 pointerDownPos;
|
|
bool pointerDown = false;
|
|
float prevPinchDistance = -1;
|
|
Vector3 dragWorldStart;
|
|
|
|
void Update()
|
|
{
|
|
HandleCameraMovement();
|
|
HandleZoom();
|
|
}
|
|
|
|
void HandleCameraMovement()
|
|
{
|
|
Vector2 inputPos = Vector2.zero;
|
|
bool pressed = false;
|
|
|
|
if (Application.isMobilePlatform && Touchscreen.current != null)
|
|
{
|
|
var touch = Touchscreen.current.primaryTouch;
|
|
|
|
if (touch.press.isPressed)
|
|
{
|
|
inputPos = touch.position.ReadValue();
|
|
pressed = true;
|
|
}
|
|
}
|
|
else if (Mouse.current != null)
|
|
{
|
|
if (Mouse.current.leftButton.isPressed)
|
|
{
|
|
inputPos = Mouse.current.position.ReadValue();
|
|
pressed = true;
|
|
}
|
|
}
|
|
|
|
if (!pressed)
|
|
{
|
|
pointerDown = false;
|
|
isDragging = false;
|
|
return;
|
|
}
|
|
|
|
Camera cam = Camera.main;
|
|
|
|
if (!pointerDown)
|
|
{
|
|
pointerDown = true;
|
|
pointerDownPos = inputPos;
|
|
|
|
dragWorldStart = cam.ScreenToWorldPoint(
|
|
new Vector3(inputPos.x, inputPos.y, -cam.transform.position.z)
|
|
);
|
|
|
|
return;
|
|
}
|
|
|
|
if (!isDragging)
|
|
{
|
|
if (Vector2.Distance(inputPos, pointerDownPos) < 5f)
|
|
return;
|
|
|
|
isDragging = true;
|
|
}
|
|
|
|
Vector3 currentWorld = cam.ScreenToWorldPoint(
|
|
new Vector3(inputPos.x, inputPos.y, -cam.transform.position.z)
|
|
);
|
|
|
|
Vector3 movement = dragWorldStart - currentWorld;
|
|
cam.transform.position += movement;
|
|
}
|
|
|
|
void HandleZoom()
|
|
{
|
|
if (Application.isMobilePlatform && Touchscreen.current != null)
|
|
{
|
|
var touches = Touchscreen.current.touches;
|
|
if (touches.Count >= 2)
|
|
{
|
|
Vector2 pos1 = touches[0].position.ReadValue();
|
|
Vector2 pos2 = touches[1].position.ReadValue();
|
|
|
|
if (touches[0].press.isPressed && touches[1].press.isPressed)
|
|
{
|
|
float currentDist = Vector2.Distance(pos1, pos2);
|
|
if (prevPinchDistance > 0)
|
|
{
|
|
float diff = currentDist - prevPinchDistance;
|
|
Camera.main.orthographicSize = Mathf.Clamp(Camera.main.orthographicSize - (diff * 0.1f), 1f, 100f);
|
|
}
|
|
prevPinchDistance = currentDist;
|
|
return;
|
|
}
|
|
}
|
|
prevPinchDistance = -1;
|
|
}
|
|
else
|
|
{
|
|
float scroll = Mouse.current.scroll.ReadValue().y;
|
|
if (scroll != 0)
|
|
{
|
|
if (Keyboard.current.leftCtrlKey.isPressed)
|
|
{
|
|
Camera.main.orthographicSize = Mathf.Clamp(Camera.main.orthographicSize - scroll, 1f, 100f);
|
|
}
|
|
else
|
|
{
|
|
var pos = Camera.main.transform.position;
|
|
pos.y += scroll * 5f;
|
|
Camera.main.transform.position = pos;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|