C# – How to get x and y coordinates from a linear grid simply


I have myself a linear grid of Vector2s stored in a Vector2[,] array, and i also have another Vector2 that lies within this grid. How can i simply extract both the nearest 4 grid points and their indexes in the array? I'm totally stumped…

Best Solution

I'm not sure if I'm understanding your question. Can you handle it in a relatively straightforward way?

  1. Declare a type to hold the following information:
    a. Integer index into your existing Vector2 array
    b. Distance that the point is from the test vector
    c. (optional) The Vector2 value.
  2. Declare an array of the newly defined type to contain the results.
  3. Loop through the existing array of Vector2s.
  4. For each Vector2, calculate its distance from the test vector.
  5. Compare that distance to the last result Vector2. If it is less than that distance, replace that result vector with the current Vector2's information.
  6. While the distance of the last result vector is less than the previous one, swap it with the previous result. (Repeat with the same vector, now in the second-to-last position until the result vectors are sorted in order of distance from the test vector.)
  7. Proceed with the next iteration of the loop started in step 3.