1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| public class PlaceObjectOnGrid : MonoBehaviour
{
public Transform gridCellPrefab;
public Transform cube;
public Transform onMousePrefabe;
public Vector3 smoothMousePosition;
[SerializeField] private int height;
[SerializeField] int width;
private Vector3 mousePosition;
private Node[,] nodes;
private Plane plane;
void Start()
{
CreateGrid();
plane = new Plane(Vector3.up, transform.position);
}
void Update()
{
GetMousePositionOnGrid();
}
void GetMousePositionOnGrid()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out var enter))
{
mousePosition = ray.GetPoint(enter);
print(mousePosition);
smoothMousePosition = mousePosition;
mousePosition.y = 0;
mousePosition = Vector3Int.RoundToInt(mousePosition);
foreach (var node in nodes)
{
if (node.cellPosition == mousePosition && node.isPlaceable)
{
if (Input.GetMouseButtonUp(0) && onMousePrefabe != null)
{
node.isPlaceable = false;
onMousePrefabe.GetComponent<ObjFollowMouse>().isOnGrid = true;
onMousePrefabe.position = node.cellPosition + new Vector3(0, 0.5f, 0);
onMousePrefabe = null;
}
}
}
}
}
public void OnMouseClickOnUI()
{
// if (onMousePrefabe == null)
{
onMousePrefabe = Instantiate(cube, mousePosition, Quaternion.identity);
}
}
private void CreateGrid()
{
nodes = new Node[width, height];
var name = 0;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
Vector3 worldPosition = new Vector3(i, 0, j);
Transform obj = Instantiate(gridCellPrefab, worldPosition, Quaternion.identity);
obj.name = "Cell " + name;
nodes[i, j] = new Node(true, worldPosition, obj);
name++;
}
}
}
public class Node
{
public bool isPlaceable;
public Vector3 cellPosition;
public Transform obj;
public Node(bool isPlaceable, Vector3 cellPosition, Transform obj)
{
this.isPlaceable = isPlaceable;
this.cellPosition = cellPosition;
this.obj = obj;
}
}
} |
Partager