该代码基于LeanTouch插件进行的开发,可在触摸屏上操作,亦可使用键盘Alt+鼠标左键模拟双指
using UnityEngine;
using Lean.Touch;
using DG.Tweening;
public class CameraController : MonoBehaviour
{
// 旋转速度
public float rotationSpeed = 0.5f;
// 移动速度
public float moveSpeed = 0.1f;
// 最小Field of View值
public float minFieldOfView = 20f;
// 最大Field of View值
public float maxFieldOfView = 100f;
// 相机的位置
private Vector3 cameraPosition;
// 上一次手指触摸的时间
private float lastTouchTime = 0f;
// 是否开启自动旋转
private bool isAutoRotating = true;
public Camera _cam;
private void Start()
{
_cam = GetComponent<Camera>();
// 初始化相机位置和距离
cameraPosition = transform.position;
distance = (transform.position - transform.parent.position).magnitude;
// 订阅LeanTouch.OnFingerUpdate事件
LeanTouch.OnFingerUpdate += OnFingerUpdate;
}
private void OnDestroy()
{
// 取消订阅LeanTouch.OnFingerUpdate事件
LeanTouch.OnFingerUpdate -= OnFingerUpdate;
}
private void Update()
{
// 如果超过十秒没有手指触摸,则自动旋转相机
if (Time.time - lastTouchTime > 10f)
{
isAutoRotating = true;
}
if (isAutoRotating)
{
// 缓慢将相机旋转值的x和z归0
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0f, transform.rotation.eulerAngles.y, 0f), Time.deltaTime);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0f), Time.deltaTime);
// 自动旋转相机
transform.RotateAround(transform.parent.position, Vector3.up, rotationSpeed * Time.deltaTime * 3);
// 缓慢将Field of View值返回至60
_cam.fieldOfView = Mathf.Lerp(_cam.fieldOfView, 80f, Time.deltaTime);
}
}
private void OnFingerUpdate(LeanFinger finger)
{
// 更新手指触摸时间
lastTouchTime = Time.time;
// 检测手指的数量
if (LeanTouch.Fingers.Count == 1)
{
float MoveX = Input.GetAxis("Mouse X") * 5;
float MoveY = Input.GetAxis("Mouse Y") * 5;
//if (transform.rotation.eulerAngles.y + MoveX > 305 || transform.rotation.eulerAngles.y + MoveX < 55)
transform.Rotate(new Vector3(0, MoveX, 0), Space.World);
if (transform.rotation.eulerAngles.x - MoveY < 45 || transform.rotation.eulerAngles.x - MoveY > 315)
transform.Rotate(new Vector3(-MoveY, 0, 0), Space.Self);
// 关闭自动旋转
isAutoRotating = false;
}
else if (LeanTouch.Fingers.Count == 2)
{
// 获取手指的移动量
Vector2 delta = finger.ScreenDelta;
// 计算相机的Field of View值
float fieldOfView = _cam.fieldOfView - delta.y * moveSpeed;
fieldOfView = Mathf.Clamp(fieldOfView, minFieldOfView, maxFieldOfView);
// 更新相机的Field of View值
_cam.fieldOfView = fieldOfView;
isAutoRotating = false;
}
}
}