日志
是时候用我们写的PathFinder做一些很酷的事了,首先我们来拓展一下人物的移动,之前已经完成了使用键盘实现
自由的移动,现在我们再来写一个常见的用鼠标实现智能寻路移动。
MouseController
人物要监听很多有关鼠标的操作,不只是点击地面移动,还有点击敌人、点击拾取物品,以及当鼠标放在某物体上时可能需要有特殊的效果(高亮显示等),所以我们创建一个单独的controller来负责和鼠标相关的输入控制。
void FixedUpdate()
{
Ray ray = viewController.CurrentViewCam.ScreenPointToRay(Input.mousePosition);
RaycastHit raycastHit;
if(Physics.Raycast(ray, out raycastHit))
{
string infoStr = "";
if(raycastHit.collider.CompareTag("Evil") && raycastHit.collider.GetComponentInParent<Attackable>())
{
infoStr += " 攻击";
if(Input.GetMouseButtonDown(0))
{
attackController.attackTarget = raycastHit.collider.GetComponentInParent<Attackable>();
attackController.attackTargetLastPos = GridPos.GetGridPos(attackController.attackTarget.transform.position);
attackController.MoveToEnemy();
}
}
if(raycastHit.collider.CompareTag("Ground"))
{
if(Input.GetMouseButtonDown(0))
{
locomotionController.MoveToPoint(raycastHit.point);
}
}
}
}
这里使用tag还是layer进行判断我纠结了挺长时间的,最后使用tag的原因是我觉得layer最有用的地方在于它可以忽略某些射线的检测,而这里并不需要这样做。
可以看到在移动的代码中只有一个关键的函数MoveToPoint,实际上攻击的部分也主要使用了这个函数
/// <summary>
/// 开启协程移动至某点
/// </summary>
/// <param name="dst"></param>终点
public void MoveToPoint(Vector3 dst)
{
if(currentMove != null)
{
StopCoroutine(currentMove);
currentMove = null;
moveDoneCallback?.Invoke(false);
}
List<Vector3> path = MapManager.instance.FindPath(transform.position, dst);
#if DEBUG
Debug.Log(transform.position);
Vector3 last = transform.position;
foreach (var item in path)
{
GameObject go = new GameObject();
go.transform.position = item;
Debug.DrawLine(last, item, Color.red, 180);
last = item;
}
Debug.Log(dst);
#endif
currentMove = StartCoroutine(AutoMove(path));
}
private IEnumerator AutoMove(List<Vector3> path)
{
foreach (var item in path)
{
while(!MoveToPos(item)) yield return null;
}
currentMove = null;
moveDoneCallback?.Invoke(true);
}
private bool MoveToPos(Vector3 dst)
{
Vector3 direction = dst - transform.position;
direction.y = 0;
direction.Normalize();
viewController.model.transform.LookAt(new Vector3(dst.x, transform.position.y, dst.z));
if(transform.position.PlanerDistance(dst) > 0.05f)
{
transform.position += direction * Time.deltaTime * runSpeed;
animator.SetInteger("MoveState", 1);
return false;
}
else return true;
}
moveInterruption是别的模块对人物自由移动的监听,比如移动需要打断攻击等。
moveDoneCallback是结束时的回调,因为定点移动往往是别的模块交付的人物,他们自然需要监听移动的结果。
新的MoveToPosition请求也会先终止之前的协程。
AttackController
攻击分为三个步骤,搜寻目标、跑向目标、攻击,如果使用F键的话我们自动搜寻周围的目标,使用鼠标点击则是指定目标,所以当我们按下F时应当调用搜索目标的函数,然后在每帧中检测如果有目标就移向目标和检测是否在攻击范围内尝试攻击
void FixedUpdate()
{
if(Input.GetKeyDown(KeyCode.F))
{
FindTarget();
MoveToEnemy();
}
if(attackTarget)
{
//如果敌人移动了就需要重新计算路线,否则就只检测是否能进行攻击
GridPos attackTargetPos = GridPos.GetGridPos(attackTarget.transform.position);
if(!attackTargetPos.Equal(attackTargetLastPos))
{
MoveToEnemy();
attackTargetLastPos = attackTargetPos;
}
CheckAttack();
}
}
/// <summary>
/// 寻找距离最近的可攻击目标(带有attackable组件)
/// </summary>
void FindTarget()
{
attackTarget = null;
attackTargetLastPos = null;
Attackable[] targets = FindObjectsOfType<Attackable>();
float minDistance = float.MaxValue;
Attackable closestTarget = null;
foreach(var target in targets)
{
float distance = transform.position.PlanerDistance(target.transform.position);
if(distance < minDistance)
{
minDistance = distance;
closestTarget = target;
}
}
if(closestTarget && minDistance <= tryAttackDistance)
{
attackTarget = closestTarget;
attackTargetLastPos = GridPos.GetGridPos(attackTarget.transform.position);
}
}
这里有几个很重要的问题,第一寻路是非常消耗性能的,所以我们应该尽可能少的进行寻路,所以应该判断目标是否移动了位置,如果没有移动位置就不进行新的寻路,移动位置后就需要重新规划路径并打断之前的移动协程进行新协程。
第二checkattack是每物理帧进行的检测,如果已经在我们攻击范围内就不需要再向前走,直接打断协程进行攻击,但我们需要判断是否正在进行攻击,否则就会在可攻击时每帧重复调用Attack,攻击并没有采用冷却时间的计量方法,而是直接以动画播放来表示攻击的过程,采用animation event对敌人造成伤害(还没写),所以我们可以直接获取是否播放动画来查看是否在攻击。
public bool IsAttacking
{
get { return animator.GetCurrentAnimatorStateInfo(1).IsName("Attack"); }
}
void CheckAttack()
{
if(transform.position.PlanerDistance(GetAttackPos()) < attackDistance)
{
if(locomotionController.currentMove != null)
{
StopCoroutine(locomotionController.currentMove);
locomotionController.currentMove = null;
}
if(!IsAttacking) Attack();
}
}
void Attack()
{
animator.SetTrigger("Attack");
//长按f表示想要继续攻击同一个目标,所以如果长按f就不将目标置空,之后就会继续检测攻击
if(!Input.GetKey(KeyCode.F))
{
attackTarget = null;
attackTargetLastPos = null;
if(locomotionController.currentMove != null)
{
StopCoroutine(locomotionController.currentMove);
locomotionController.currentMove = null;
locomotionController.moveDoneCallback -= OnChaseDone;
}
}
}
此外要考虑到我们的攻击目标可能体积巨大,他的坐标是它的中心,但我们并不需要攻击它的中心点,而是碰撞体边缘最近的一点,所以使用射线检测来确定最近的攻击位置也是移动目的地。
/// <summary>
/// 使用协程向目标点移动并记录终点
/// </summary>
public void MoveToEnemy()
{
locomotionController.MoveToPoint(GetAttackPos());
locomotionController.moveDoneCallback += OnChaseDone;
}
//获取攻击目标的可攻击点
//我们要对能与目标碰撞的最近的地方发起攻击而不是目标的中心点(因为目标可能拥有一个很大的collider)
Vector3 GetAttackPos()
{
float minY = Mathf.Min(transform.position.y, attackTarget.transform.position.y);
Vector3 origin = new Vector3(transform.position.x, 0.1f, transform.position.z);
Vector3 dst = new Vector3(attackTarget.transform.position.x, 0.1f, attackTarget.transform.position.z);
RaycastHit[] raycastHits = Physics.RaycastAll(origin, dst - origin, Vector3.Distance(origin, dst));
foreach(var item in raycastHits)
{
if(item.collider.gameObject == attackTarget.gameObject)
{
//Debug.Log(item.point);
return item.point;
}
}
return transform.position;
}
我们必须时刻关注在LocomotionController中开启的协程,因为它是别的模块托管的功能,需要由托管的模块开始、结束、接收回调等