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