我为2D网格开发脚本,以及#34;生活"在3D环境中。网格模型是二维数组。网格应该是 可修改 - 支持改变位置,比例和旋转。其中一个必需的函数是获取网格索引(array [i,j]) 在鼠标上。旋转为0,0,0时脚本正常工作。移动和缩放都没有问题,但如果旋转网格,则返回错误的索引。我使用transform.InverseTransformPoint将鼠标的世界位置转换为网格上的本地坐标。
脚本的相关部分:
using UnityEngine;
using System.Collections;
public class GridManager: MonoBehaviour {
//...
public float tileSize = 0.6f; //tile size, tile width == tile hight
private Object[, ] grid;
private Vector3 gridBottomLeftLocal;
void Start() {
//...
//grid start position is 0, y, 0
gridBottomLeftLocal = new Vector3 (-gridSizeX / 2, transform.position.y, -gridSizeY / 2);
}
void Update() {
Vector3 mousePos;
if (getMousePosition(out mousePos)) {
Debug.Log ("Hit");
Vector2 tile = getTileByWorldPos(mousePos);
Debug.Log ("Pos: " + tile);
}
}
//TODO: check for out of grid bounds
Vector2 getTileByWorldPos (Vector3 worldPos) {
Vector3 localPos = transform.InverseTransformPoint(worldPos);
Vector3 offset = localPos - gridBottomLeftLocal;
int x = (offset.x % tileSize == 0) ? (int)(offset.x / tileSize) - 1: (int)(offset.x / tileSize);
int y = (offset.z % tileSize == 0) ? (int)(offset.z / tileSize) - 1: (int)(offset.z / tileSize);
return new Vector2 (x, y);
}
private bool getMousePosition(out Vector3 mousePos) {
Vector3 a = transform.position + Vector3.forward;
Vector3 b = transform.position + Vector3.right;
Vector3 c = transform.position + new Vector3 (1,0,1);
Plane plane = new Plane (a, b, c);
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
float enter;
bool isHit = plane.Raycast (ray, out enter);
mousePos = isHit ? ray.GetPoint (enter) : Vector3.zero;
return isHit;
}
}