操作 | 光标图案 | 效果 |
按住鼠标中键拖动 | 手掌 | 平移视野 |
按住鼠标右键拖动 | 眼睛 | 旋转视野 |
滚鼠标滚轮 | 光标没变 | 放大缩小(步长固定) |
键盘Alt+鼠标右键,拖动鼠标 | 放大镜 | 放大缩小(均匀、连续) |
本文用代码实现上面这些效果,让您在的应用使用起来像是在用Unity。其实原理比较简单,为了让大家节省点时间我还是分享一下吧~~。你可以这样想:
操作 | 光标图案 | 效果 |
按住鼠标中键拖动 | 手掌 | Camera的x、y坐标变化,移动距离取决于鼠标拖动距离 |
按住鼠标右键拖动 | 眼睛 | Camera绕x、y轴旋转而z轴的转角始终为0,转角取决于鼠标拖动距离 |
滚鼠标滚轮 | 光标没变 | Camera沿z轴前进、后退,步长固定 |
键盘Alt+鼠标右键,拖动鼠标 | 放大镜 | Camera沿z轴前进、后退,移动距离取决于鼠标拖动距离 |
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);//单单按鼠标右键旋转相机的速度
public Texture2D m_texture2D1, m_texture2D2, m_texture2D3, m_texture2D4;//光标图案
private void FixedUpdate()
{
MouseEvents();
}
void MouseEvents()
{
//按住鼠标右键拖动
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);
Cursor.SetCursor(m_texture2D4, new Vector2(5, 5), CursorMode.ForceSoftware);
}
//单单按鼠标右键
else
{
transform.eulerAngles += rotateDelta;
Cursor.SetCursor(m_texture2D1, new Vector2(5, 5), CursorMode.ForceSoftware);
}
}
}
//按住鼠标中键拖动
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);
Cursor.SetCursor(m_texture2D3, new Vector2(5, 5), CursorMode.ForceSoftware);
}
}
//如果没有按鼠标除了滚滚轮的键,则实时更新光标“上一次”的位置mouseLastPosition
else
{
mouseLastPosition = Input.mousePosition;//重新赋初值
Cursor.SetCursor(m_texture2D2, new Vector2(5, 5), CursorMode.ForceSoftware);//更改鼠标图标
}
//滚轮——放大缩小
if (Input.mouseScrollDelta.y != 0)//滚轮滚了多少
transform.Translate(new Vector3(0, 0, Time.deltaTime * mouseScrollSpeed * Input.mouseScrollDelta.y), Space.Self);
}
}
上面的代码里各种速度你可以随意设,设完后自己测试调一下就好了,我的速度值也不一定最好。光标图案用图片,分辨率在25~30为宜(分辨率的高度和宽度最大的那个在25~30之间,不在这个范围内也无所谓),注意要把图片的Texture Type设为Cursor,不改的话调试窗口会有警告。
我把C#脚本挂在相机上,拖进去一些图标