问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Unity实现360度可旋转、缩放单独看模型

创作时间:
2025-03-15 17:13:39
作者:
@小白创作中心

Unity实现360度可旋转、缩放单独看模型

引用
CSDN
1.
https://m.blog.csdn.net/weixin_48388330/article/details/138290070

本文介绍如何在Unity中实现一个可以360度旋转和缩放的模型展示功能。通过自定义脚本控制模型的旋转和缩放,结合鼠标交互实现直观的模型查看体验。

一、说明

实现模型的单独交互,显示在面板上,可以进行旋转和缩放操作。

二、代码演示

using UnityEngine;

public class ModelShowControl : MonoBehaviour
{
    [SerializeField][Header("渲染展示相机")]
    private GameObject showCamera;
    [SerializeField][Header("展示交互的物品")]
    private GameObject showGameObject;
    
    [SerializeField][Header("是否自动旋转")]
    private bool isAutoRotate;
    [SerializeField][Header("自动旋转方向,例如(0,1,0)按照Y轴旋转")]
    private Vector3 autoRotateDirection;
    [SerializeField][Header("是否按照自身坐标系轴自动旋转")]
    private bool isAutoRotatePivot;
    [SerializeField][Header("自动旋转速度")]
    private float autoRotationSpeed = 5; 
    [SerializeField][Header("鼠标旋转速度")]
    private float mouseRotateSpeed = 0.5f;
    [SerializeField][Header("是否反向旋转X")]
    private bool isRotateInvertX;
    [SerializeField][Header("是否反向旋转Y")]
    private bool isRotateInvertY;
    [SerializeField][Header("缩放速度")]
    private float zoomSpeed = 0.5f;
    [SerializeField][Header("是否反向缩放")]
    private bool isZoomInvert;
    [SerializeField][Header("最近缩放距离")]
    private float minZoomDistance = 1f;
    [SerializeField][Header("最远缩放距离")]
    private float maxZoomDistance = 10f;
    
    private Vector3 cameraInitPos;
    private Vector3 lastMousePosition;
    private bool isRotating; //是否正在旋转
    private Vector3[] showGameObjectInitTrans = new Vector3[3];
    
    public static ModelShowControl Instance;
    private void Awake()
    {
        Instance = this;
        cameraInitPos = showCamera.transform.position;
    }
    public void SetShowGameObject(GameObject _gameObject)
    {
        showGameObjectInitTrans[0] = _gameObject.transform.position;
        showGameObjectInitTrans[1] = _gameObject.transform.eulerAngles;
        showGameObjectInitTrans[2] = _gameObject.transform.localScale;
        showGameObject = _gameObject;
        showCamera.transform.position = cameraInitPos;
    }
    public void RestoreShowGameObject()
    {
        showGameObject.transform.position = showGameObjectInitTrans[0];
        showGameObject.transform.eulerAngles = showGameObjectInitTrans[1];
        showGameObject.transform.localScale = showGameObjectInitTrans[2];
        showGameObject = null;
        showCamera.transform.position = cameraInitPos;
        isRotating = false;
    }
    void Update()
    {
        if (showGameObject == null)
            return;
        if (isAutoRotate && !Input.GetMouseButton(0)) // 如果鼠标左键没按下
            RotateModelContinuously(); // 持续旋转模型
        else
            RotateModelOnMouseDrag(); // 根据鼠标拖拽旋转模型
        ZoomCamera();
    }
    void RotateModelContinuously()
    {
        if (!isAutoRotatePivot)
            showGameObject.transform.Rotate(autoRotateDirection, autoRotationSpeed * Time.deltaTime, Space.World);
        else
        {
            var rotateEuler = autoRotateDirection * autoRotationSpeed * Time.deltaTime;
            // 根据模型当前朝向构造一个围绕轴旋转的四元数
            Quaternion deltaRotation = Quaternion.Euler(rotateEuler);
            // 将新的旋转应用到模型
            showGameObject.transform.rotation *= deltaRotation;
        }
    }
    void RotateModelOnMouseDrag()
    {
        if (Input.GetMouseButtonDown(0))
        {
            isRotating = true;
            lastMousePosition = Input.mousePosition;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            isRotating = false;
        }
        if (isRotating && (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0))
        {
            Vector3 currentMousePosition = Input.mousePosition;
            Vector3 mouseDeltaPosition = currentMousePosition - lastMousePosition;
        
            float rotationX = -mouseDeltaPosition.y * mouseRotateSpeed;
            float rotationY = mouseDeltaPosition.x * mouseRotateSpeed;
            showGameObject.transform.Rotate(Vector3.up, isRotateInvertX ? rotationY : -rotationY, Space.World);
            showGameObject.transform.Rotate(Vector3.right, isRotateInvertY ? rotationX : -rotationX, Space.World);
            lastMousePosition = currentMousePosition;
        }
    }
    void ZoomCamera()
    {
        // 获取鼠标滚轮的滚动值
        float scrollWheelInput = Input.GetAxis("Mouse ScrollWheel");
        if (scrollWheelInput == 0) return;
        // 计算缩放后的相机距离
        float zoomDistance = showCamera.transform.localPosition.z -
                             scrollWheelInput * (isZoomInvert ? zoomSpeed : -zoomSpeed);
        zoomDistance = Mathf.Clamp(zoomDistance, -maxZoomDistance, -minZoomDistance);
        // 设置相机距离
        showCamera.transform.localPosition = new Vector3(cameraInitPos.x, cameraInitPos.y, zoomDistance);
    }
}  

三、使用说明

  1. 设置一个需要显示交互的模型相机
  2. 将相机拖入ShowCamera中,需要展示的模型可以在运行时直接放入,需要使用
SetShowGameObject(showGameObject);//调用方法

也可以运行时添加显示模型:

ModelShowControl.Instance.SetShowGameObject(showGameObject);//调用方法

配合鼠标射线检测进行如下调用(要展示的模型设置Tag为ModelShow):

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ModelShowManager : MonoBehaviour
{
    public GameObject modelShowGameObjectParent;
    public GameObject modelShowPanel;
    public Button closeModelShowPanelBtn;
    private void Awake()
    {
        closeModelShowPanelBtn.onClick.AddListener(() =>
        {
            modelShowPanel.SetActive(false);
            ModelShowControl.Instance.RestoreShowGameObject();
        });
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            
            if (Physics.Raycast(ray, out hitInfo))
            {
                if (hitInfo.collider.CompareTag("ModelShow"))
                {
                    modelShowPanel.SetActive(true);
                    
                    for (int i = 0; i < modelShowGameObjectParent.transform.childCount; i++)
                    {
                        var child = modelShowGameObjectParent.transform.GetChild(i).gameObject;
                        if (child.name == hitInfo.collider.gameObject.name)
                        {
                            child.SetActive(true);
                            ModelShowControl.Instance.SetShowGameObject(child);
                        }
                        else
                        {
                            child.SetActive(false);
                        }
                    }
                }
            }
        }
    }
}
  1. 添加一个New Render Texture给相机上
  2. 添加Image的UI,创建一个材质,选择
    将New Render Texture赋给该材质,然后将材质赋给Image

四、演示结果

现在就可以360度显示模型,可以鼠标交互旋转缩放。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号