【发布时间】:2016-04-08 05:08:14
【问题描述】:
我在 Unity 中有一个 2D 瓦片游戏项目,其中每个瓦片的大小为(例如)32 x 32 像素,但在网格中瓦片映射到完整的整数坐标,例如 tile0 位于 @987654322 @,tile1 位于 x1 y0,tile2 位于 x2 y0,tile10 位于 x2 y1,依此类推(如果我没记错的话,这个映射是由于将 pixel per unit size 设置为将精灵表设置为例如 32px,对吗?)
无论如何,玩家应该能够用鼠标向左/向右/向上/向下拖动瓷砖,我希望瓷砖随着鼠标位置一起拖动。我遇到的问题是我不知道如何将全局鼠标坐标转换为拖动图块的局部空间,特别是转换为 -1 和 1 之间的范围,因为拖动距离已标准化为该范围。
在我的Update() 方法中,我有这个代码:
if (_isMouseDown && sourceTile != null)
{
_isDraggingTile = true;
Vector3 dragDistance = Input.mousePosition - _originMousePosition;
dragDistance.Normalize();
GridCell targetCell;
/* Check mouse up/down drag. */
float f = Vector3.Dot(dragDistance, Vector3.up);
if (f >= 0.5f)
{
targetCell = sourceTile.gridCell.upNeighbor;
}
else if (f <= -0.5f)
{
targetCell = sourceTile.gridCell.downNeighbor;
}
else
{
/* Check mouse left/right drag. */
f = Vector3.Dot(dragDistance, Vector3.right);
targetCell = f >= 0.5f ? sourceTile.gridCell.rightNeighbor : sourceTile.gridCell.leftNeighbor;
}
if (Vector3.Distance(_originMousePosition, Input.mousePosition) > _globals.tileDragThreshold)
{
if (targetCell != null)
{
SetTargetTile(targetCell.tile);
ResolveMove();
}
}
}
代码检查鼠标拖动到哪个方向,并在某个阈值后将拖动的图块切换到相邻网格单元中的图块 (targetCell)。我想要实现的是拖动的图块跟随鼠标位置直到交换发生。
谁能给我一个提示,告诉我如何将鼠标位置转换成这个,以便相应地调整拖动的图块的位置?
【问题讨论】:
标签: c# unity3d 2d mouse game-engine