Search Unity

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

Discussion in 'Scripting' started by flipwon, Oct 25, 2019.

  1. flipwon

    flipwon

    Joined:
    Dec 29, 2016
    Posts:
    179
    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:
    Code (CSharp):
    1. public List<Node> GetNodesInRadius(Vector3 startPos, float radius)
    2.     {
    3.         List<Node> nodeList = new List<Node>();
    4.         int x = Mathf.RoundToInt(startPos.x);
    5.         int y = Mathf.RoundToInt(startPos.y);
    6.         int z = Mathf.RoundToInt(startPos.z);
    7.         int r = Mathf.RoundToInt(radius);
    8.  
    9.         for (int i = x - r; i <= x + r; i++)
    10.         {
    11.             //for (int j = y - r; j <= y + r; y++)
    12.             //{
    13.                 for (int k = z - r; k <= z + r; k++)
    14.                 {
    15.                     if (Vector3.Distance(new Vector3(i, 0, k), startPos) <= r)
    16.                     {
    17.                         var nodeToAdd = GetNodeFromVector3(new Vector3(i, 0, k));
    18.                         if (nodeToAdd != null)
    19.                             nodeList.Add(nodeToAdd);
    20.                     }
    21.                 }
    22.             //}
    23.         }
    24.      
    25.         return nodeList;
    26.     }
    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 :D
     
    Last edited: Oct 25, 2019
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    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?
     
  3. flipwon

    flipwon

    Joined:
    Dec 29, 2016
    Posts:
    179
    It just hangs indefinitely, and running in debug doesn't seem to give any information at all.
     
  4. flipwon

    flipwon

    Joined:
    Dec 29, 2016
    Posts:
    179
    Scratch that, it was a simple syntax error. I was incrementing y instead of j. Will leave up in shame anyways
     
    Doug_B and darax like this.