目录
基于:【Unity3D】Tilemap俯视角像素游戏案例-CSDN博客
2D玩家添加Dotween移动DOPath效果,移动完成后进行刷新小地图(小地图会顺便刷新大地图)
一、玩家脚本Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class Player : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector2 pos = Input.mousePosition;
Ray ray = Camera.main.ScreenPointToRay(pos);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
if (hit.collider != null)
{
Vector2 hitPos = hit.point;
Vector3Int v3Int = new Vector3Int(Mathf.FloorToInt(hitPos.x), Mathf.FloorToInt(hitPos.y), 0);
List<Vector3Int> pathPointList = GameLogicMap.Instance.PlayAstar(v3Int);
Vector3[] pathArray = new Vector3[pathPointList.Count];
int offset = pathPointList.Count - 1;
for (int i = pathPointList.Count - 1; i >= 0; i--)
{
Vector3Int pointPos = pathPointList[i];
Vector3 worldPos = GameLogicMap.Instance.GetWorldPos(pointPos);
pathArray[offset - i] = worldPos;
}
transform.DOPath(pathArray, 1f).OnComplete(() =>
{
Debug.Log("移动完成 更新小地图");
GameLogicMap.Instance.DrawSmallMap();
}).SetAutoKill(true);
}
}
}
public Vector3Int GetPos()
{
Vector3 pos = transform.position;
return new Vector3Int(Mathf.FloorToInt(pos.x - 0.5f), Mathf.FloorToInt(pos.y - 0.5f), 0);
}
}
二、Canvas组件设置
三、小地图相关
原理:利用2D游戏为了实现寻路而创建的二维数组去生成一张Texture2D纹理图,大地图是直接用int[,]map二维数组去创建,map[x,y]等于1是空地,不等于1是障碍物或不可穿越地形;
大地图上的玩家绿点是直接拿到玩家在map的坐标点直接绘制。
小地图是以玩家为中心的[-smallSize/2, smallSize/2]范围内进行绘制;小地图上的玩家绿点是直接绘制到中心点(smallSize.x/2, smallSize.y/2);
注意:绘制到Texture2D的像素点坐标是[0, size]范围的,则小地图的绘制是SetPixel(i, j, color),传递i, j是[0,size]范围的,而不要传递x, y,这个x,y的取值是以玩家点为中心的[-size/2, size/2]范围坐标值,如下取法:
x = 玩家点.x - size.x/2 + i;
y = 玩家点.y - size.y/2 + j;
用2层for遍历来看的话就是从(玩家点.x - size.x/2, 玩家点.y - size.y/2)坐标点,从下往上,从左往右依次遍历每个map[x,y]点生成对应颜色的像素点,构成一张Texture2D图片。
usi