Getting points in a 3d grid within a radius. WTB maths

Hey guys!

I’m currently trying to brute force my way into getting all valid nodes in the radius of my player on a 3d grid. My code is working when looping through just the x and the z plane, but when I add the y to check vertical space as well unity craps itself and crashes. I’m not sure what to do as my math brain left me many years ago, so I’m confused as to where I’m going wrong/how to fix this.

The code:

public List<Node> GetNodesInRadius(Vector3 startPos, float radius)
    {
        List<Node> nodeList = new List<Node>();
        int x = Mathf.RoundToInt(startPos.x);
        int y = Mathf.RoundToInt(startPos.y);
        int z = Mathf.RoundToInt(startPos.z);
        int r = Mathf.RoundToInt(radius);

        for (int i = x - r; i <= x + r; i++)
        {
            //for (int j = y - r; j <= y + r; y++)
            //{
                for (int k = z - r; k <= z + r; k++)
                {
                    if (Vector3.Distance(new Vector3(i, 0, k), startPos) <= r)
                    {
                        var nodeToAdd = GetNodeFromVector3(new Vector3(i, 0, k));
                        if (nodeToAdd != null)
                            nodeList.Add(nodeToAdd);
                    }
                }
            //}
        }
     
        return nodeList;
    }

So, a node is simple a simple object that holds it’s position in a vector 3 and what’s inside of it etc. The GetNodeFromVector3 method does just that, get’s a node at the location.

This does return my nodes on the x and z coordinates, but it doesn’t seem to like me uncommenting that y block and swapping those 0’s with j’s lol…

Any idea why this is crashing unity? Any thoughts on how to make this faster with the maths?

Thanks in advance :smile:

Do you have any details on the crash - is there an exception or any error messages? Does it just hang indefinitely? If you run in the debugger, do you get a useful call stack back into the code above and, if so, what line is it at?

It just hangs indefinitely, and running in debug doesn’t seem to give any information at all.

Scratch that, it was a simple syntax error. I was incrementing y instead of j. Will leave up in shame anyways

2 Likes