实现角色冲刺效果
本章为选做效果。在 2D 游戏中,冲刺是一个很常见的效果。
学习目标
完成本教程后,您将学会:
- 实现角色的冲刺效果
操作流程
修改代码
- 添加
private bool isDashing = false;
作为冲刺标识 - 修改 ProcessInput
csharp
private void ProcessInput()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
bool isDash = Input.GetKey(KeyCode.Space);
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
if (movement.magnitude > 1)
{
movement.Normalize();
}
if (isDash && !isDashing && movement != Vector2.zero)
{
isDashing = true;
Debug.Log("Dashing");
DoDashAnimation();
rb.linearVelocity = movement * 10f; // 冲刺速度
Invoke("StopDashing", 0.4f); // 停止冲刺的延时
}
else if (!isDashing)
{
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 if (!isDashing)
{
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
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
- 添加 StopDashing 方法
csharp
private void StopDashing()
{
isDashing = false;
}
1
2
3
4
2
3
4
- 添加 DoDashAnimation 方法
csharp
private void DoDashAnimation()
{
transform.DOScale(new Vector3(1.3f, 0.7f, 1f), 0.1f);
transform.DOScale(new Vector3(1f, 1f, 1f), 0.15f).SetDelay(0.1f);
}
1
2
3
4
5
2
3
4
5
测试
- 点击 Play 打开游戏
- 点击空格,检查是否有冲刺效果与动画。
概念解析
Inovke
Invoke 接受两个参数,第一个是方法名,第二个是执行延迟,它允许你将方法的执行延后。
在本文中,StopDashing 被延后了 0.4s 执行。
transform.DOScale
这是 DOTWeen 提供的拓展方法,它允许对 Scale 属性进行插值动画。在本文中,它可以将原本 (1,1,1) 的 Scale 在 0.1s 内插值变为 (1.3,0.7,1)。
DOTWeen 的方法大多采用链式调用,其中 SetDelay 可以为动画设置执行延迟。