如何从世界位置的贴图数组中获取贴图(寻径?)



我在不同的地方发现了这样的解决方案,每个地方他们都有不同的方法,我试图重新创建他们的解决方案,但它不能正常工作。解决方案=祝辞

Debug.DrawRay(ray.origin, ray.direction * 100f, Color.red, 5f);
RaycastHit2D hit;
var result = Physics2D.Raycast(ray.origin, ray.direction, 100f);
if (result)
{
Debug.Log(ray);
float percentegeX = (result.point.x + width / 2) / width;
float percentegeY = (result.point.y + height / 2) / height;
percentegeX = Mathf.Clamp01(percentegeX);
percentegeY = Mathf.Clamp01(percentegeY);
x = Mathf.RoundToInt((countX - 1) * percentegeX);
y = Mathf.RoundToInt((countY - 1) * percentegeY);
return board[x, y];

这个代码是塞巴斯蒂安拉格,它工作得很好与相等的矩形。但是我有这个=>

board = new GameTileContent[countX, countY];

cellWidth = 3;
cellHeight = 4;
width = cellWidth * countX + (spacing.x * countX);
height = cellHeight * countY + (spacing.y * countY);
leftEdge = transform.position - Vector3.right * width / 2 - Vector3.up * height / 2;
for (int x = 0; x < countX; x++)
{
for (int y = 0; y < countY; y++)
{
Vector3 position = new Vector3((x * cellWidth + cellWidth / 2f) + leftEdge.x + (x * (spacing.x * countX)),
(y * cellHeight + cellHeight / 2f) + leftEdge.y + (y * (spacing.y * countY)), 1f);
var obj = Instantiate(prefabTile, transform);
board[x, y] = obj;
obj.x = x;
obj.y = y;
obj.type = GameTileContent.EType.EMPTY;
obj.transform.localScale = new Vector3(cellWidth, cellHeight);
obj.transform.position = position;
obj.gameObject.AddComponent<BoxCollider2D>();
}
}

我有cellWidth 3和cellHeight 4如何从网格瓷砖计算正确的方式?我可能只使用光线投射,但它不会更快,对吗?在这种情况下会发生什么呢?显然,舍入是不正确的,当我单击2:0的tile的边缘时,得到的数据是1.94和0.66,然后舍入到2.1 tile。如果我手动设置四舍五入的条件,那么它或多或少是正确的,但这是错误的方法吗?如果这个重要的链接到视频https://youtu.be/nhiFx28e7JY?t=1197与时间轴

您可以使用鼠标/触摸点击位置来计算触摸的世界位置,然后在您的tilemap上使用WorldToCell方法来获得tile坐标。

var pointerPosition = Input.mousePosition;
pointerPosition = Camera.main.ScreenToWorldPoint(pointerPosition);
pointerPosition.z = 0;
var gridPosition = groundTileMap.WorldToCell(pointerPosition);
if (!groundTileMap.HasTile(gridPosition))
{
Debug.LogError($"{TAG} No tile");
return;
}

最新更新