using System.Collections; using System.Collections.Generic; using UnityEngine; public class touchControls : MonoBehaviour { public float rotationSpeed = 0.2f; // 旋转速度 private float xRotation; // X轴旋转角度 private float yRotation; // Y轴旋转角度 public float minYRotation = 0f; // Y轴最小旋转角度 public float maxYRotation = 90f; // Y轴最大旋转角度 private Vector2 lastTouchPosition; // 上一次触摸/鼠标的位置 private bool isDragging = false; // 标记是否正在拖动 void Update() { #if UNITY_EDITOR // 仅在编辑器模式下使用鼠标模拟 HandleMouseInput(); #else // 在设备上使用触摸输入 HandleTouchInput(); #endif } // 鼠标输入处理函数(用于Unity编辑器中测试) private void HandleMouseInput() { if (Input.GetMouseButtonDown(0)) // 按下鼠标左键 { lastTouchPosition = Input.mousePosition; isDragging = true; } else if (Input.GetMouseButtonUp(0)) // 松开鼠标左键 { isDragging = false; } if (isDragging) { // 计算拖动的差异 Vector2 delta = (Vector2)Input.mousePosition - lastTouchPosition; // 计算旋转量 float rotationX = delta.x * rotationSpeed; float rotationY = -delta.y * rotationSpeed; // 更新旋转角度 xRotation += rotationX; yRotation += rotationY; // 限制Y轴旋转角度范围 yRotation = Mathf.Clamp(yRotation, minYRotation, maxYRotation); // 应用旋转 transform.rotation = Quaternion.Euler(yRotation, xRotation, 0); // 更新上一次触摸的位置 lastTouchPosition = Input.mousePosition; } } // 触摸输入处理函数(用于实际设备测试) private void HandleTouchInput() { if (Input.touchCount > 0) { Touch touch = Input.GetTouch(0); // 获取第一个触摸点 if (touch.phase == TouchPhase.Began) { // 记录初始触摸位置 lastTouchPosition = touch.position; } else if (touch.phase == TouchPhase.Moved) { // 计算拖动的差异 Vector2 delta = touch.position - lastTouchPosition; // 计算旋转量 float rotationX = delta.x * rotationSpeed; float rotationY = -delta.y * rotationSpeed; // 更新旋转角度 xRotation += rotationX; yRotation += rotationY; // 限制Y轴旋转角度范围 yRotation = Mathf.Clamp(yRotation, minYRotation, maxYRotation); // 应用旋转 transform.rotation = Quaternion.Euler(yRotation, xRotation, 0); // 更新上一次触摸的位置 lastTouchPosition = touch.position; } } } }