制作第一个可移动角色
学习目标
完成本教程后,您将学会:
- 导入和设置 2D 角色精灵
- 添加物理系统和碰撞检测
- 编写角色移动控制脚本
操作流程
1. 创建角色对象
- 在 Hierarchy 视窗中,右键
2D Object Sprites Square - 点击新创建的角色,在 Inspector 窗口中重命名为 Character
- 在 Inspector 窗口中,点击 Add Component,添加 Rigidbody 2D 和 Box Collider 2D 组件。
- 将 Rigidbody 2D 的 Gravity Scale 设为 0,因为我们是 2D 俯视角游戏,不需要处理重力。
- 在 Add Component 中,输入 Player Controller,点击 New Script 新建脚本,进入 IDE 进行脚本编辑。
2. 编写移动逻辑
csharp
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public static PlayerController Instance { get; private set; } // 单例模式,后续讲设计模式时会另作解释。
private Rigidbody2D rb;// 2D刚体组件
private Vector2 mousePosition;// 鼠标位置
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(gameObject);
}
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);// 获取屏幕位置
ProcessInput();// 处理输入
}
private void ProcessInput()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
if (movement.magnitude > 1)
{
movement.Normalize();// 向量归一化
}
rb.linearVelocity = movement * 5f;
if (movement != Vector2.zero)
{
var mouse = mousePosition - (Vector2)transform.position;
// 计算旋转角度,保证物体面朝鼠标方向
float angle = Mathf.Atan2(mouse.y, mouse.x) * Mathf.Rad2Deg;
// 设置玩家的旋转
rb.rotation = angle;
}
else
{
rb.linearVelocity = Vector2.zero; // 停止移动
}
}
}
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
测试
- 点击 Play 按钮,开始游戏
- 输入 WASD,测试是否正常移动。
概念解释
Rigidbody2D 2D 刚体
2D 刚体是 Unity 物理引擎中的组件,用于处理受力,速度,碰撞等。
其中的 linearVelocity 属性为其位移速度,是一个二维矢量 (Vector 2)
Box Collider 2D 2D 盒形碰撞器
盒形碰撞器为物体提供了一个矩形的碰撞范围,当刚体与其接触时产生影响。(可以理解为,为物体设定了一个矩形的碰撞体积)
Unity 声明周期
所有继承了 MonoBehaviour 的类,都可以使用 Unity 的生命周期函数,它将在物体的不同生命周期自动地去执行函数内的功能。
文中的 Update 方法,它代表该方法会每帧执行
文中的 Awake 方法,它仅在脚本初始化时执行,且只执行一次。
Start 方法,仅在脚本初始化完成后的第一帧开始执行。
顺序: Awake - Start - Update,详情可自己查询文档
Input.GetAxis
返回由 axisName 标识的虚拟轴的值。
对于键盘和游戏杆输入设备,该值将处于 -1...1 的范围内。
该值的含义取决于输入控制的类型,例如,对于游戏杆的水平轴,值为 1 表示游戏杆向右推到底,值为 -1 表示游戏杆向左推到底;值为 0 表示游戏杆处于中性位置。
如果玩家向左移动键盘或游戏手柄,该值将为负;如果玩家向右移动,该值将为正。