天天看點

Unity滑鼠控制物體的旋轉、移動、縮放等

Unity滑鼠控制物體的旋轉、移動、縮放等
  • Input.GetMouseButton(0)

    擷取滑鼠輸入,參數為一個int值

    為0的時候擷取的是左鍵

  • Input.GetMouseButton(1)

    為1的時候擷取的是右鍵

  • Input.GetMouseButton(2)

    為2的時候擷取的是中鍵(就是那個滑輪)

  • Input.GetMouseButton

    滑鼠點選

  • Input.GetMouseButtonUp

    滑鼠松開

  • Input.GetMouseButtonDown

    滑鼠按壓

  • Camera.main.ScreenToWorldPoint

    螢幕坐标轉化為世界坐标

  • Quaternion rotation = Quaternion.Euler(0, 0, 0);

    歐拉角轉化為四元數

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

public class MouseControlModel : MonoBehaviour
{
    //旋轉最大角度
    public int yMinLimit = -20;
    public int yMaxLimit = 80;
    //旋轉速度
    public float xSpeed = 250.0f;
    public float ySpeed = 120.0f;
    //旋轉角度
    private float x = 0.0f;
    private float y = 0.0f;

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            //将螢幕坐标轉化為世界坐标  ScreenToWorldPoint函數的z軸不能為0,不然傳回錄影機的位置,而Input.mousePosition的z軸為0
            //z軸設成10的原因是錄影機坐标是(0,0,-10),而物體的坐标是(0,0,0),是以加上10,正好是轉化後物體跟錄影機的距離
            Vector3 temp = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));
            transform.position = temp;
        }
        else if (Input.GetMouseButton(1))
        {
            //Input.GetAxis("MouseX")擷取滑鼠移動的X軸的距離
            x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
            y = ClampAngle(y, yMinLimit, yMaxLimit);
            //歐拉角轉化為四元數
            Quaternion rotation = Quaternion.Euler(y, x, 0);
            transform.rotation = rotation;
        }
        else if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            //滑鼠滾動滑輪 值就會變化
            if (Input.GetAxis("Mouse ScrollWheel") < 0)
            {
                //範圍值限定
                if (Camera.main.fieldOfView <= 100)
                    Camera.main.fieldOfView += 2;
                if (Camera.main.orthographicSize <= 20)
                    Camera.main.orthographicSize += 0.5F;
            }
            //Zoom in  
            if (Input.GetAxis("Mouse ScrollWheel") > 0)
            {
                //範圍值限定
                if (Camera.main.fieldOfView > 2)
                    Camera.main.fieldOfView -= 2;
                if (Camera.main.orthographicSize >= 1)
                    Camera.main.orthographicSize -= 0.5F;
            }
        }
    }

    //角度範圍值限定
    static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

           

繼續閱讀