提取公共方法

我们将PlayerController的Animator引用提取到它的父类Controller中,并且将其中的SetBlend(改名前叫做SetAnimTreeBlend)方法提取到父类Controller中,父类中的SetBlend是个虚方法,这样子类Controller通过覆写它就能实现不同的角色控制效果。

我们将PlayerController的isMove、dir、Dir变量和属性提取到它的父类Controller

Controller

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
using UnityEngine;

namespace DarknessWarGodLearning
{
public abstract class Controller : MonoBehaviour
{
protected bool isMove = false;
private Vector2 dir = Vector2.zero;
public Vector2 Dir
{
get => dir; set
{
if (value == Vector2.zero)
{
isMove = false;
}
else
{
isMove = true;
}
dir = value;
}
}

public Animator playerAnimator;
public virtual void SetBlend(float blend)
{
playerAnimator.SetFloat("Blend", blend);
}
}
}

PlayerController删除掉之前的Animator引用,并且重载虚方法

1
2
3
4
public override void SetBlend(float blend)
{
targetBlend = blend;
}

修改状态类

修改StateIdle

1
2
3
4
public void Process(EntityBase entity)
{
entity.SetBlend(Constants.BlendIdle);
}

修改State

1
2
3
4
public void Process(EntityBase entity)
{
entity.SetBlend(Constants.BlendMove);//将BlendWalk改名为BlendMove
}

前面我们说过,状态类会作用于逻辑实体,而逻辑实体引用了自己的controller,让controller来承担表现逻辑。

接下来,只需要在BattleMgr里面修改EntityPlayer就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void SetSelfPlayerMoveDir(Vector2 dir)
{
//设置玩家移动
if(dir == Vector2.zero)
{
entitySelfPlayer.Idle();
entitySelfPlayer.SetDir(Vector2.zero);
}
else
{
entitySelfPlayer.Move();
entitySelfPlayer.SetDir(dir);
}
}