- 思路:首先是获取到鼠标按下后的移动距离数值和滚轮的数值,进而利用数值更新
- unity 场景对象结构如下,是两层结构,复制脚本后放在第一层
![](https://i-blog.csdnimg.cn/direct/9bc1bcfdaeaf47159175d0ec96cea206.png)
using System.Collections.Generic;
using UnityEngine;
public class CamerControl : MonoBehaviour
{
//检测中键键是否按下
private bool IsMouseDown = false;
//存储移动距离, x,y轴
private Dictionary<string, (float, float)> MoveDistance;
//开始位置
private Vector3 Startpositions;
//实时位置
private Vector3 Nowpositions;
//移动速度
public float MoveSpeed;
//旋转速度
public float RotateSpeed;
//相机推进速度
public float ScaleSpeed;
private void Start()
{
//初始化移动距离
MoveDistance = new Dictionary<string, (float, float)>
{
{ "Distance", (0, 0) },
};
transform.LookAt(transform.position);
}
private void Update()
{
//鼠标按下检测
if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2))
{
IsMouseDown = true;
Startpositions = Input.mousePosition;
}
//鼠标按下并移动,记录移动距离
if (IsMouseDown && (Input.GetMouseButton(0) || Input.GetMouseButton(1) || Input.GetMouseButton(2)))
{
Nowpositions = Input.mousePosition;
MoveDistance["Distance"] = (Nowpositions.x - Startpositions.x, Nowpositions.y - Startpositions.y);
}
//移动功能
if (IsMouseDown && Input.GetMouseButton(2) && Nowpositions != Startpositions)
{
transform.Translate(Vector3.right * MoveDistance["Distance"].Item1*0.01f*-1*MoveSpeed);
transform.Translate(Vector3.forward * MoveDistance["Distance"].Item2 * 0.01f*-1*MoveSpeed);
Startpositions = Input.mousePosition;
}
//旋转功能
else if (IsMouseDown && Input.GetMouseButton(0) && Nowpositions != Startpositions)
{
transform.Rotate(Vector3.up, MoveDistance["Distance"].Item1 * 0.1f*RotateSpeed, Space.World);
Startpositions = Input.mousePosition;
}
//相机推进或后退功能
if (Input.mouseScrollDelta.y != 0)
{
transform.GetChild(0).position += transform.GetChild(0).transform.forward * Input.mouseScrollDelta.y * Time.deltaTime * 100 * ScaleSpeed;
}
//鼠标弹起
if (Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1) || Input.GetMouseButtonUp(2))
{
IsMouseDown = false;
MoveDistance["Distance"] = (0, 0);
}
else return;
}
}