MyBook/Assets/script/ModelRotationHandler.cs
2025-03-22 15:17:36 +08:00

57 lines
2.1 KiB
C#
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using UnityEngine.EventSystems;
public class ModelRotationHandler : MonoBehaviour, IPointerDownHandler, IDragHandler
{
public Transform modelTransform; // 需要旋转的3D模型的父节点
    public float rotationSpeed = 5f; // 旋转速度
    public float zoomSpeed = 20f; // 缩放速度
    public float minZoom = -10f; // 最小缩放距离
    public float maxZoom = -2f;  // 最大缩放距离
    public GameObject GameObject_r_y;
public GameObject GameObject_r_x;
public GameObject Camera_pos_z; // 需要缩放的相机对象
    private Vector2 lastMousePosition; // 记录上一次鼠标位置
    public void OnPointerDown(PointerEventData eventData)
{
lastMousePosition = eventData.position; // 记录鼠标初始位置
    }
public void OnDrag(PointerEventData eventData)
{
if (modelTransform == null) return;
Vector2 delta = eventData.position - lastMousePosition; // 计算鼠标移动量
        float rotationX = -delta.y * rotationSpeed * Time.deltaTime;
float rotationY = delta.x * rotationSpeed * Time.deltaTime;
GameObject_r_x.transform.Rotate(Vector3.up, rotationY, Space.World); // 水平旋转(左右拖动)
        GameObject_r_y.transform.Rotate(Vector3.right, rotationX, Space.World); // 垂直旋转(上下拖动)
        lastMousePosition = eventData.position; // 更新鼠标位置
    }
void Update()
{
if (modelTransform == null) return;
GameObject_r_y.transform.position = modelTransform.position;
if (Camera_pos_z == null) return;
float scroll = Input.GetAxis("Mouse ScrollWheel");
if (scroll != 0f)
{
Vector3 targetPos = Camera_pos_z.transform.localPosition;
targetPos.z += scroll * zoomSpeed;
targetPos.z = Mathf.Clamp(targetPos.z, minZoom, maxZoom);
            // 使用 Lerp 进行平滑缩放
            Camera_pos_z.transform.localPosition = Vector3.Lerp(Camera_pos_z.transform.localPosition, targetPos, Time.deltaTime * 20f);
}
}
}