【极简代码】Unity控制3D物体的自由旋转 缩放和移动

  • Post author:
  • Post category:其他

Unity中以最少代码,控制3D物体的自由旋转、缩放和移动。

using UnityEngine;

public class TestMatrix : MonoBehaviour
{
    float scaleparam = 0f;
    Vector3 oldScale;

    private void Start()
    {
        oldScale = transform.localScale;
    }

    private void Update()
    {
        void Trans_Rotation()
        {
            float mouse_x = -Input.GetAxis("Mouse X");//鼠标X轴移动
            float mouse_y = Input.GetAxis("Mouse Y");//鼠标Y轴移动
            if (Input.GetMouseButton(0))
            {
                transform.RotateAround(transform.position, Vector3.up, mouse_x * 10);
                transform.RotateAround(transform.position, -Vector3.right, -mouse_y * 10);
            }
        }
        Trans_Rotation();//自由旋转

        
        void Trans_Scale()
        {
            if (Input.GetAxis("Mouse ScrollWheel") != 0f)
            {
                scaleparam += Input.GetAxis("Mouse ScrollWheel");
                Vector3 newScale = new Vector3(Mathf.Clamp(oldScale.x+ scaleparam,0f,100f), Mathf.Clamp(oldScale.y + scaleparam, 0f, 100f), Mathf.Clamp(oldScale.z + scaleparam, 0f, 100f));
                transform.localScale =newScale;                
            }
        }
        Trans_Scale();//缩放

        void Trans_Mv()
        {
            if (Input.GetMouseButton(1))
            {
                Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
                Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z);
                transform.position = Camera.main.ScreenToWorldPoint(mousePos);
            }
        }
        Trans_Mv();//移动
    }

}



版权声明:本文为qq_39889893原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。