详细代码:
using UnityEngine;
public class CameraControl : MonoBehaviour
{
public Transform target; // 中心点位置
public float rotateSpeed = 0.5f;
public float zoomSpeed = 1.0f;
public float minZoom = 5.0f;
public float maxZoom = 20.0f;
public float minVerticalAngle = 10.0f;
public float maxVerticalAngle = 80.0f;
private Vector2 lastPanPosition;
private int panFingerId; // Touch mode only
public float currentZoom = 10.0f;
public float currentYaw = 0.0f;
public float currentPitch = 45.0f;
void Start()
{
currentZoom = Mathf.Clamp(currentZoom, minZoom, maxZoom);
}
void Update()
{
if (Input.touchCount == 1)
{
// 单指触摸控制旋转
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
lastPanPosition = touch.position;
panFingerId = touch.fingerId;
}
else if (touch.fingerId == panFingerId && touch.phase == TouchPhase.Moved)
{
Vector2 delta = touch.position - lastPanPosition;
currentYaw += delta.x * rotateSpeed;
currentPitch -= delta.y * rotateSpeed;
currentPitch = Mathf.Clamp(currentPitch, minVerticalAngle, maxVerticalAngle);
lastPanPosition = touch.position;
}
}
else 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;
currentZoom -= difference * zoomSpeed;
currentZoom = Mathf.Clamp(currentZoom, minZoom, maxZoom);
}
}
void LateUpdate()
{
Vector3 direction = new Vector3(0, 0, -currentZoom);
Quaternion rotation = Quaternion.Euler(currentPitch, currentYaw, 0);
transform.position = target.position + rotation * direction;
transform.LookAt(target);
}
}