- Home /
Clear a circle on a game map build from an int[x,y] array
I have a game map created from int[,] map that contains either a 1 or a 0 in an x and y coordinate. I want to clear an area of the map (i.e. set all coordinates in a circle pattern to 0) regardless of what it was set to before.
I figure I could run through each x y coordinate on the map and work out if it's distance from the x,y center coordinate is in range of the size - however I am unsure if my math calculation is the right away to do it and if the code is correct.
To demonstrate I have created an image to show (1) the existing int array (2) the coordinates I want to be changed by sending an x,y and an int circleSize (3) the result by changing all of these x,y's to zeros.
I have also supplied the function I have tried and confused myself on. The int[,] map is already assigned 1's and 0's.
void ClearCircleOnMap(int startX, int startY, int circleSize){
for (int x = startX - circleSize; x < startX + circleSize; x++){
for (int y = startY - circleSize; y < startY + circleSize; y++){
map[x,y] = (Mathf.Sqrt((Mathf.Pow(startX - x,2f)) + (Mathf.Pow(startY - y,2f)) < circleSize)) ? 1 : map[x,y];
}
}
}
I was trying to use the a squared + b squared = c squared and seeing if that is less that the circleSize (radius from center). I realise now too one of the problems is I should be getting the magnitude and comparing it to the circleSize value - but I think my logic may be flawed from the start and there would be an easier way to do it anyway.
Answer by seandolan · Jan 04, 2018 at 01:42 PM
Here was the solution:
void ClearCircleOnMap(int startX, int startY, int circleSize){
Debug.Log (startX - circleSize);
Debug.Log (startX + circleSize);
for (int x = startX - circleSize; x < startX + circleSize; x++){
for (int y = startY - circleSize; y < startY + circleSize; y++){
//map[x,y] = (Mathf.Sqrt(Mathf.Pow(x,2f) + (Mathf.Pow(y,2f))) < circleSize) ? 1 : map[x,y];
if (x > 0 && x < mapWidth - 1 && y > 0 && y < mapHeight - 1) {
if (Mathf.Sqrt (Mathf.Pow (startX - x, 2f) + Mathf.Pow (startY - y, 2f)) < circleSize) {
map [x, y] = 0;
}
}
}
}
}