最近有朋友问我想实现跟scene视图一样的鼠标操作控制,所以我网上看了一看,找了个例子,稍微修改一下,成了下面这个
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraAction : MonoBehaviour
{
public float mouseScrollSpeed = 40, //滚滚轮放大缩小速度
mouseDragSpeed1 = 10, //单单按右键旋转的速度
mouseDragSpeed2 = 1.26f;//按中键移动的速度
public Vector3 mouseLastPosition = new Vector3(0, 0, 0), //“上一次”光标的位置
mousePositionDelta = new Vector3(0, 0, 0);//光标位置变化量,等于现在光标位置减上一次光标的位置
Vector3 rotateDelta = new Vector3(0, 0, 0);//单单按鼠标右键旋转相机的速度
private void FixedUpdate()
{
MouseEvents();
}
private bool isWDown = false;
void MouseEvents()
{
if (Input.GetKey(KeyCode.W)||Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(Vector3.forward * Time.deltaTime * 10);
}
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(Vector3.back * Time.deltaTime * 10);
}
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(Vector3.left * Time.deltaTime * 10);
}
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(Vector3.right * Time.deltaTime * 10);
}
//按住鼠标右键拖动
if (Input.GetMouseButton(1))
{
mousePositionDelta = Input.mousePosition - mouseLastPosition;
mouseLastPosition = Input.mousePosition;
if (mousePositionDelta.magnitude != 0)
{
rotateDelta = new Vector3(-mousePositionDelta.y * Time.deltaTime * mouseDragSpeed1,
mousePositionDelta.x * Time.deltaTime * mouseDragSpeed1, 0);
//按Alt+鼠标右键
if (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))
{
this.transform.Translate(new Vector3(0, 0, Time.deltaTime * mouseScrollSpeed * (rotateDelta.x + rotateDelta.y)), Space.Self);
}
//单单按鼠标右键
else
{
transform.eulerAngles += rotateDelta;
}
}
}
//按住鼠标中键拖动
else if (Input.GetMouseButton(2))
{
mousePositionDelta = Input.mousePosition - mouseLastPosition;
mouseLastPosition = Input.mousePosition;
if (mousePositionDelta.magnitude != 0)
{
rotateDelta = new Vector3(-mousePositionDelta.x * Time.deltaTime * mouseDragSpeed2,
-mousePositionDelta.y * Time.deltaTime * mouseDragSpeed2, 0);
transform.Translate(rotateDelta, Space.Self);
}
}
//如果没有按鼠标除了滚滚轮的键,则实时更新光标“上一次”的位置mouseLastPosition
else
{
mouseLastPosition = Input.mousePosition;//重新赋初值
}
//滚轮——放大缩小
if (Input.mouseScrollDelta.y != 0)//滚轮滚了多少
transform.Translate(new Vector3(0, 0, Time.deltaTime * mouseScrollSpeed * Input.mouseScrollDelta.y), Space.Self);
}
}
希望对大家有用,谢谢