using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 手指或鼠标控制摄像机旋转 /// 使用方法:将此脚本挂到Camera上 /// </summary> public class TouchRotationCamera : MonoBehaviour { public float aroundSpeed = 0.1f; //旋转速度 public bool aroundX = true; //允许绕X轴旋转 public bool aroundY = true; //允许绕Y轴旋转 private Vector3 lastPosition; private Transform cacheTransfrom; private bool isMobilePlatform; void Awake() { cacheTransfrom = transform; isMobilePlatform = WebJS.IsMobilePlatform; } void LateUpdate() { //注意: //发布WebGL平台时,需借助JavaScript来判断浏览器运行平台。 if (Application.platform == RuntimePlatform.WebGLPlayer) { if (isMobilePlatform) TouchRotation(); else MouseRotation(); return; } //设备是否支持触摸 if (Input.touchSupported) { TouchRotation(); } //是否探测到鼠标 else if (Input.mousePresent) { MouseRotation(); } } void MouseRotation() { if (Input.GetMouseButtonDown(0)) { lastPosition = Input.mousePosition; return; } if (!Input.GetMouseButton(0)) return; Vector3 mousePosition = Input.mousePosition; Vector3 offset = mousePosition - lastPosition; float t = -offset.x; offset.x = offset.y; offset.y = t; offset.z = 0; if (!aroundX) offset.x = 0; if (!aroundY) offset.y = 0; Vector3 euler = cacheTransfrom.eulerAngles; euler.x += offset.x * aroundSpeed; euler.y += offset.y * aroundSpeed; cacheTransfrom.eulerAngles = euler; lastPosition = mousePosition; } void TouchRotation() { int touchCount = Input.touchCount; if (touchCount <= 0) return; Vector3 firstTouch = Input.touches[0].position; if (Input.touches[0].phase == TouchPhase.Began) { lastPosition = firstTouch; return; } Vector3 offset = firstTouch - lastPosition; float t = -offset.x; offset.x = offset.y; offset.y = t; if (!aroundX) offset.x = 0; if (!aroundY) offset.y = 0; Vector3 euler = cacheTransfrom.eulerAngles; euler.x += offset.x * aroundSpeed; euler.y += offset.y * aroundSpeed; cacheTransfrom.eulerAngles = euler; lastPosition = firstTouch; } }