Unity通过鼠标操作来控制场景视角(包括旋转、平移以及缩放) 您所在的位置:网站首页 答疑3dmax物体怎么进行左右同步变换的操作方法 Unity通过鼠标操作来控制场景视角(包括旋转、平移以及缩放)

Unity通过鼠标操作来控制场景视角(包括旋转、平移以及缩放)

2023-09-26 17:00| 来源: 网络整理| 查看: 265

首先,本博客转自该博客 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. 问题

问题:为了更改视角变化的幅度,需要加上一个比例因子,但是定义变量,然后使用变量去改变视角变化率,会发现没有变化,直接使用数字是可行的,后来发现需要使用静态变量,否则变量可能“读不到”,比较坑



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有