129 lines
3.2 KiB
C#
129 lines
3.2 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class RotateAndScale : MonoBehaviour
|
|
{
|
|
[Header("旋转设置")]
|
|
public float rotationSpeed = 0.2f; // 旋转速度
|
|
private bool isRotating = false;
|
|
private Vector3 lastMousePos;
|
|
|
|
[Header("拖拽设置")]
|
|
public float dragSpeed = 0.01f;
|
|
private bool isDragging = false;
|
|
|
|
[Header("缩放设置")]
|
|
public float scaleSpeed = 0.5f; // 缩放速度
|
|
public float minScale = 0.1f; // 最小缩放
|
|
|
|
[Header("复位按钮")]
|
|
public Button resetButton;
|
|
|
|
// 初始状态记录
|
|
private Vector3 initialPosition;
|
|
private Quaternion initialRotation;
|
|
private Vector3 initialScale;
|
|
|
|
private void Start()
|
|
{
|
|
// 记录初始状态
|
|
initialPosition = transform.position;
|
|
initialRotation = transform.rotation;
|
|
initialScale = transform.localScale;
|
|
|
|
if (resetButton != null)
|
|
{
|
|
resetButton.onClick.RemoveAllListeners();
|
|
resetButton.onClick.AddListener(ResetTransform);
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
HandleRotation();
|
|
HandleDragging();
|
|
HandleScaling();
|
|
}
|
|
|
|
// 页面重新进入时调用,重置输入状态
|
|
public void ResetInput()
|
|
{
|
|
isRotating = false;
|
|
isDragging = false;
|
|
}
|
|
|
|
private void HandleRotation()
|
|
{
|
|
if (Input.GetMouseButtonDown(1))
|
|
{
|
|
isRotating = true;
|
|
lastMousePos = Input.mousePosition;
|
|
}
|
|
|
|
if (Input.GetMouseButtonUp(1))
|
|
{
|
|
isRotating = false;
|
|
}
|
|
|
|
if (isRotating)
|
|
{
|
|
Vector3 delta = Input.mousePosition - lastMousePos;
|
|
|
|
// 根据鼠标移动旋转:横向控制 Y 轴,纵向控制 X 轴
|
|
float rotationX = delta.y * rotationSpeed;
|
|
float rotationY = -delta.x * rotationSpeed;
|
|
|
|
transform.Rotate(Vector3.up, rotationY, Space.World);
|
|
transform.Rotate(Vector3.right, rotationX, Space.World);
|
|
|
|
lastMousePos = Input.mousePosition;
|
|
}
|
|
}
|
|
|
|
private void HandleDragging()
|
|
{
|
|
if (Input.GetMouseButtonDown(0))
|
|
{
|
|
isDragging = true;
|
|
lastMousePos = Input.mousePosition;
|
|
}
|
|
|
|
if (Input.GetMouseButtonUp(0))
|
|
{
|
|
isDragging = false;
|
|
}
|
|
|
|
if (isDragging)
|
|
{
|
|
Vector3 delta = Input.mousePosition - lastMousePos;
|
|
transform.Translate(new Vector3(delta.x, delta.y, 0) * dragSpeed, Space.World);
|
|
lastMousePos = Input.mousePosition;
|
|
}
|
|
}
|
|
|
|
private void HandleScaling()
|
|
{
|
|
float scroll = Input.mouseScrollDelta.y;
|
|
if (Mathf.Abs(scroll) > 0f)
|
|
{
|
|
Vector3 newScale = transform.localScale + Vector3.one * scroll * scaleSpeed;
|
|
newScale.x = Mathf.Max(newScale.x, minScale);
|
|
newScale.y = Mathf.Max(newScale.y, minScale);
|
|
newScale.z = Mathf.Max(newScale.z, minScale);
|
|
transform.localScale = newScale;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 点击复位按钮时调用
|
|
/// </summary>
|
|
public void ResetTransform()
|
|
{
|
|
transform.position = initialPosition;
|
|
transform.rotation = initialRotation;
|
|
transform.localScale = initialScale;
|
|
|
|
ResetInput(); // 同时清除鼠标输入状态
|
|
}
|
|
}
|