Unity通过鼠标操作来控制场景视角(包括旋转、平移以及缩放)
生活随笔
收集整理的這篇文章主要介紹了
Unity通过鼠标操作来控制场景视角(包括旋转、平移以及缩放)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先,本博客轉自該博客?https://www.cnblogs.com/machine/p/unity.html?,在此記錄只是為了防止博客刪除或者書簽找不到,所以重新在此記錄一下。
1. 在攝像頭“Main Camera”的底部“Add Component”中添加一個腳本,然后添加以下代碼
using System.Collections; using System.Collections.Generic; using UnityEngine;public class sceneinsight : MonoBehaviour {// 模型public Transform car_model;// 旋轉速度public static float rotateSpeed = 10f; //一定要使用static,不然可能變量值讀不到public static float rotateLerp = 8;// 移動速度public static float moveSpeed = 0.5f;public static float moveLerp = 10f;// 鏡頭拉伸速度public static float zoomSpeed = 10f; //速度比例因子public static float zoomLerp = 4f; //阻尼系數,有個緩沖作用// 計算移動private Vector3 position, targetPosition;// 計算旋轉private Quaternion rotation, targetRotation;// 計算距離private float distance, targetDistance;// 默認距離private const float default_distance = 5f;void Start(){// 旋轉歸零targetRotation = Quaternion.identity;// 初始位置是模型targetPosition = car_model.position;// 初始鏡頭拉伸targetDistance = default_distance;}void Update(){//Debug.Log("camera button ");float dx = Input.GetAxis("Mouse X");float dy = Input.GetAxis("Mouse Y");// 鼠標左鍵移動if (Input.GetMouseButton(0)){dx *= moveSpeed;dy *= moveSpeed;targetPosition -= transform.up * dy + transform.right * dx;}// 鼠標右鍵旋轉if (Input.GetMouseButton(1)){dx *= rotateSpeed;dy *= rotateSpeed;if (Mathf.Abs(dx) > 0 || Mathf.Abs(dy) > 0){// 獲取攝像機歐拉角Vector3 angles = transform.rotation.eulerAngles;// 歐拉角表示按照坐標順序旋轉,比如angles.x=30,表示按x軸旋轉30°,dy改變引起x軸的變化angles.x = Mathf.Repeat(angles.x + 180f, 360f) - 180f;angles.y += dx;angles.x -= dy;// 計算攝像頭旋轉targetRotation.eulerAngles = new Vector3(angles.x, angles.y, 0);}}// 鼠標滾輪拉伸targetDistance -= Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;}private void FixedUpdate(){rotation = Quaternion.Slerp(rotation, targetRotation, Time.deltaTime * rotateLerp);position = Vector3.Lerp(position, targetPosition, Time.deltaTime * moveLerp);distance = Mathf.Lerp(distance, targetDistance, Time.deltaTime * zoomLerp);// 設置攝像頭旋轉transform.rotation = rotation;// 設置攝像頭位置transform.position = position - rotation * new Vector3(0, 0, distance);} }此時關閉腳本文件,返回Unity界面的“Main Camera”的Insepector窗口可以看到剛添加的腳本下方會讓我們添加一個“Car_model”,此時可以選擇一個物體,選擇完,我們的視角則以該物體為基礎,我這里是以車為視角,如下圖,至于腳本和模型如何和攝像頭綁定則可參照我的另一篇博客 https://blog.csdn.net/yldmkx/article/details/108735252。
??
?
2. 問題
問題:為了更改視角變化的幅度,需要加上一個比例因子,但是定義變量,然后使用變量去改變視角變化率,會發現沒有變化,直接使用數字是可行的,后來發現需要使用靜態變量,否則變量可能“讀不到”,比較坑
總結
以上是生活随笔為你收集整理的Unity通过鼠标操作来控制场景视角(包括旋转、平移以及缩放)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows下各个盘中的文件夹属性变为
- 下一篇: 其它项目中引用AirSIm模块报错Nul