How can I make a circle from grid of GameObjects?

Viewed 691

What I am trying to achieve is something like this: enter image description here

What I have so far is the edges for the circles.

Expected Results

I know this would involve a nested for loop. This is what I have so far:

public GameObject player;
private GameObject playerGrid;

public int numOfObjects;
private Vector3 centerPos;
public int size = 2;

public Vector2 speed = new Vector2(50, 50);
private float smoothTime = 0.25f;

void Start()
{
    playerGrid = new GameObject();
    centerPos = transform.position;

    for (int i = 0; i < numOfObjects; i++)
    {
        float pointNum = (i * 1.0f) / numOfObjects;
        float angle = pointNum * Mathf.PI * 2;
        float r = size / 2 * (Mathf.PI); 
        float x = Mathf.Sin(angle) * r;
        float y = Mathf.Cos(angle) * r;
        Vector3 pointPos = new Vector3(x, y, 0) + centerPos;
        GameObject obj = Instantiate(player, pointPos, Quaternion.identity);
        obj.transform.SetParent(playerGrid.transform);
    }        
}

I am stuck on how to implement the conditional for the nested for loop. Also, I have trouble understanding the calculations of column positions in the nested for loop. I believe the conditional would be the start and end of I for that column or row: for(int j = i + 1; j < i - 1, j++)

For the col positions, I would think it would be incrementing the angle enough to give the square its space for that column: float x = (Mathf.Sin(angle) + somethingHere) * r;

I just not sure how to progress from here.

1 Answers

Here's a simple way to draw a circle:

public float circleRadius = 5f;
public float objectSize = 1f;

void OnDrawGizmos()
{
    for (var x = -circleRadius; x <= circleRadius; x++)
    {
        for (var y = -circleRadius; y <= circleRadius; y++)
        {
            var pos = new Vector3(x, 0f, y);
            
            if (pos.magnitude >= circleRadius) continue;

            Gizmos.DrawSphere(pos * (objectSize * 2f), objectSize);
        }
    }
}
Related