输入控制与玩家交互

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()
{
// 按下瞬间(GetKeyDown)
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}

// 按住期间(GetKey)
if (Input.GetKey(KeyCode.W))
{
MoveForward();
}

// 松开瞬间(GetKeyUp)
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;

6.2 虚拟轴(InputManager)

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()
{
// GetAxis:平滑过渡(带加速度)
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");

// GetAxisRaw:无平滑,直接返回 -1/0/1
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.mousePositionInput.GetAxis("Mouse X/Y") 处理鼠标
  • Input.touchCountTouch 结构处理触控
  • 优先使用虚拟轴而非硬编码键位

练习题

  1. 用 WASD 控制立方体前后左右移动,按住 Shift 加速
  2. 实现第一人称鼠标视角旋转(水平旋转物体,垂直旋转摄像机)
  3. 添加鼠标滚轮缩放功能(修改摄像机的 Field of View)
  4. 实现双击空格触发冲刺效果
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
Unity3D开发基础教程 系列
第 6/20 篇
分享: