1.完成AStar寻路的集成
完善AStarPathfinding中的方法,然后在GameManager中进行调用。
/// <summary>
/// 寻路方法
/// </summary>
/// <param name="e">寻路终点</param>
public void FindPath(Point e)
{
}
然后在baseElement中进行调用
/// <summary>
/// 当玩家左键点击当前元素时候执行的操作
/// </summary>
public virtual void OnLeftMouseButton()
{
GameManager._instance.FindPath(new Point(x, y));
}
2.编写扩展方法转换路径数组并寻路
新建ExtensionClass类,写List转换的扩展方法
using System.Collections.Generic;
using UnityEngine;
public static class ExtraClass
{
public static Vector3[] ToVector3Array(this List<Point> list)
{
Vector3[] v3s = new Vector3[list.Count];
for(int i = 0; i < list.Count; i++)
{
v3s[i] = new Vector3(list[i].x, list[i].y, 0);
}
return v3s;
}
}
在GameManager中完善寻路方法
/// <summary>
/// 寻路方法
/// </summary>
/// <param name="e">寻路终点</param>
public void FindPath(Point e)
{
Point s = new Point((int)player.transform.position.x, (int)player.transform.position.y);
List<Point> pathList = new List<Point>();
if (AStarPathfinding.FindPath(s, e, pathList) == false) return;
player.transform.DOPath(pathList.ToVector3Array(), pathList.Count * 0.1f);
}
3.完善寻路方法的细节
/// <summary>
/// 寻路方法
/// </summary>
/// <param name="e">寻路终点</param>
public void FindPath(Point e)
{
if(pathFinding == true) pathTweener.Kill();
Point s = new Point((int)player.transform.position.x, (int)player.transform.position.y);
List<Point> pathList = new List<Point>();
if (AStarPathfinding.FindPath(s, e, pathList) == false) return;
ResetTarget();
pathFinding = true;
pathTweener = player.transform.DOPath(pathList.ToVector3Array(), pathList.Count * 0.1f);
pathTweener.SetEase(Ease.Linear);
pathTweener.onComplete += () => {
pathFinding = false;
};
pathTweener.onKill += () => {
pathFinding = false;
};
}
4.使角色可以翻开走过的元素
完善站立区域方法
/// <summary>
/// 生成站立区域
/// </summary>
/// <param name="y">站立区域中心y坐标</param>
private void GenerateStandArea(int y)
{
for(int i = 0; i < standAreaW; i++)
{
for(int j = y - 1; j <= y + 1; j++)
{
((SingleCoveredElement)mapArray[i, j]).UncoverElementSingle();
}
}
player.transform.position = new Vector3(1, y, 0);
prePos = nowPos = player.transform.position.ToVector3Int();
mapArray[1, y].OnPlayerStand();
}
在ExtensionClass中添加新的扩展方法,转换Int型
public static Vector3 ToVector3Int(this Vector3 v)
{
int x = v.x - Mathf.FloorToInt(v.x) > 0.5f ? Mathf.CeilToInt(v.x) : Mathf.FloorToInt(v.x);
int y = v.y - Mathf.FloorToInt(v.y) > 0.5f ? Mathf.CeilToInt(v.y) : Mathf.FloorToInt(v.y);
return new Vector3(x, y, 0);
}
在GameManager的Update里面添加翻开走过
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
ResetTarget();
}
nowPos = player.transform.position.ToVector3Int();
if (prePos != nowPos)
{
mapArray[(int)nowPos.x,(int)nowPos.y].OnPlayerStand();
mapArray[(int)nowPos.x, (int)nowPos.y].OnPlayerStand();
if(mapArray[(int)nowPos.x, (int)nowPos.y].elementContent == ElementContent.Trap)
{
pathTweener.Kill();
nowPos = prePos;
player.transform.position = nowPos;
}
else
{
prePos = nowPos;
}
}
5.将移动与动画状态机关联起来