6.1 输入检测基础
Unity 提供 Input 类处理键盘、鼠标、触控等输入。
键盘输入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Jump(); }
if (Input.GetKey(KeyCode.W)) { MoveForward(); }
if (Input.GetKeyUp(KeyCode.LeftShift)) { StopSprint(); } }
|
鼠标输入
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| Input.GetMouseButtonDown(0); Input.GetMouseButton(1); Input.GetMouseButtonUp(2);
float mouseX = Input.GetAxis("Mouse X"); float mouseY = Input.GetAxis("Mouse Y");
float scroll = Input.GetAxis("Mouse ScrollWheel");
Vector3 mousePos = Input.mousePosition;
|
Unity 的 InputManager 将物理按键映射为虚拟轴,避免硬编码按键。
默认虚拟轴
| 轴名 |
默认按键 |
范围 |
| Horizontal |
A/D 或 左右方向键 |
-1 ~ 1 |
| Vertical |
W/S 或 上下方向键 |
-1 ~ 1 |
| Mouse X |
鼠标水平移动 |
每帧偏移 |
| Mouse Y |
鼠标垂直移动 |
每帧偏移 |
使用虚拟轴
1 2 3 4 5 6 7 8 9 10 11 12 13
| void Update() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical");
float hRaw = Input.GetAxisRaw("Horizontal");
Vector3 move = new Vector3(h, 0, v) * speed * Time.deltaTime; transform.Translate(move); }
|
GetAxis 适用于需要平滑过渡的操作(如摇杆),GetAxisRaw 适用于需要立即响应的操作(如键盘格斗游戏)。
6.3 触控输入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| void Update() { if (Input.touchCount > 0) { Touch touch = Input.GetTouch(0);
switch (touch.phase) { case TouchPhase.Began: Debug.Log("触摸开始"); break; case TouchPhase.Moved: Debug.Log($"移动偏移:{touch.deltaPosition}"); break; case TouchPhase.Ended: Debug.Log("触摸结束"); break; }
Vector2 touchPos = touch.position; }
for (int i = 0; i < Input.touchCount; i++) { Touch t = Input.GetTouch(i); } }
|
6.4 基础角色控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class SimplePlayerController : MonoBehaviour { [SerializeField] private float moveSpeed = 5f; [SerializeField] private float rotateSpeed = 100f;
void Update() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector3 move = new Vector3(h, 0, v).normalized; transform.Translate(move * moveSpeed * Time.deltaTime, Space.World);
float mouseX = Input.GetAxis("Mouse X"); transform.Rotate(0, mouseX * rotateSpeed * Time.deltaTime, 0);
if (Input.GetKeyDown(KeyCode.Space)) { GetComponent<Rigidbody>().AddForce(Vector3.up * 5f, ForceMode.Impulse); } } }
|
6.5 本章小结
Input.GetKey/GetKeyDown/GetKeyUp 检测键盘按键的不同状态
Input.GetAxis 获取平滑的虚拟轴输入(WASD/摇杆)
Input.mousePosition 和 Input.GetAxis("Mouse X/Y") 处理鼠标
Input.touchCount 和 Touch 结构处理触控
- 优先使用虚拟轴而非硬编码键位
练习题
- 用 WASD 控制立方体前后左右移动,按住 Shift 加速
- 实现第一人称鼠标视角旋转(水平旋转物体,垂直旋转摄像机)
- 添加鼠标滚轮缩放功能(修改摄像机的 Field of View)
- 实现双击空格触发冲刺效果