I'm writing a grid system but I have a mathematic problem with getting the node from a world position. I basically wanna snap to the node as soon as the target is inside the square around the node (the unity grid is representing the square i mean). However as you can see in the video this is not working right now.
public Node NodeFromWorldPoint(Vector3 worldPosition) {
float percentX = (worldPosition.x + (width / 2f)) / width;
float percentY = (worldPosition.z + (height / 2f)) / height;
percentX = Mathf.Clamp01(percentX);
percentY = Mathf.Clamp01(percentY);
int x = Mathf.RoundToInt((width - 1) * percentX);
int y = Mathf.RoundToInt((height - 1) * percentY);
return nodes[x, y];
}
public void CreateGrid()
{
nodes = new Node[width, height];
var name = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
Vector3 startPosition = new Vector3((width) / 2, 0, (height) / 2) - new Vector3(0.5f, 0, 0.5f);
Vector3 worldPosition = (transform.position - startPosition) + new Vector3(x, 0, y);
nodes[x, y] = new Node(true, worldPosition, x, y);
if (visualizeNodes) {
nodes[x, y].createInstance(nodeInstance);
}
name++;
}
}
}
How would I tackle this issue? What mathematical mistake have I made?
