Search code examples
c#gridpoints

C# Getting Nearby Points on a Grid within radius


I have a grid that has X and Y coordinates. On this grid I have a starting point and I want to get all nearby cells within a certain radius.

I have made made the following function that goes +1 one in each direction and returns the spots.

    public List<Point> GetLocationsStraightLine(Point fromLocation, int Distance)
    {
        var nearbySpots = new List<Point>();
        int StartDistance = 1;

        while (StartDistance < Distance)
        {
            nearbySpots.Add(new Point(fromLocation.X, (short)(fromLocation.Y - StartDistance)));
            nearbySpots.Add(new Point((short)(fromLocation.X + StartDistance), fromLocation.Y));
            nearbySpots.Add(new Point(fromLocation.X, (short)(fromLocation.Y + StartDistance)));
            nearbySpots.Add(new Point((short)(fromLocation.X - StartDistance), fromLocation.Y));

            StartDistance++;
        }

        return nearbySpots;
    }

This returns all points in a straight line from my starting point. However I want to to also grab the inbetween spots.

This is what I currently get (Sorry for the bad image)

image of points i return

However I want to be able to enter a distance of 2 and get the full square around the start location.

what i want full square with diagnonal

So I am asking is there any easy way I can get the diagonals and not just a straight line from my starting point?


Solution

  • Since it's a rectangle, you can use a very simple approach. Assuming that Distance is always positive:

    public List<Point> GetLocationsStraightLine(Point fromLocation, int Distance) {
    
        var nearbySpots = new List<Point>();
    
        for (int i = -Distance; i <= Distance; ++i)
            for (int j = -Distance; j <= Distance; ++j)
                nearbySpots.Add(new Point(fromLocation.X + j, fromLocation.Y + i));
    
        return nearbySpots;
    
    }
    

    The idea is to start at the upper left point, and add each point in the rectangle row by row, ending at the bottom right point.