- Home /
Create a circle using cubes?
Ok, using two for loops one can create a a grid of cubes, just instantiate a cube increasingly on the x and y axis. How would one do this to create a circle or a ring?
Thanks guys in advanced!
The formula for a circle is x^2 + y^2 = radius^2. That isn't to hard to rearrange into code. I might come back and write it for you if I get the time.
I don't think this is correct. I just rearranged the equation so the x value would equal x and y would equal y. This should have printed a quarter of a circle but it just made a square.
for(int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
Instantiate(cube, new Vector3(($$anonymous$$athf.Sqrt($$anonymous$$athf.Pow(y,2)+100)),$$anonymous$$athf.Sqrt($$anonymous$$athf.Pow(x,2)+100),0),Quaternion.identity);
}
}
Well, I'm still looking for a solution, but I see the error in the script above. The square root of anything to the second power (squared) is itself, so the script is just spawning a cube at x, y, 0. If I find a solution, I will let you know.
Answer by SnotE101 · Nov 10, 2014 at 04:44 AM
Thanks guys, found the answer though. I just derived the x and y values from cosine and sin.
public GameObject cube;
void Start()
{
int x, y;
int length = 50;
float angle = 0.0f;
float interval = 0.1f;
while (angle < 2 * Mathf.PI)
{
x = (int)(length * Mathf.Cos (angle));
y = (int)(length * Mathf.Sin (angle));
Instantiate(cube,new Vector3(x,y,0),Quaternion.identity);
angle += interval;
}
}
That's what I said!
You'll get a nicer looking circle if you make your interval some defined fraction of pi.
Answer by vlxmenblack · Mar 29, 2020 at 03:41 PM
what if i want it to be spawned internally rather than just creating a border? @SnotE101
Then just Random.Range(0, length) the length in order to have it spawned randomly anywhere from the center up to the border.
Answer by florinel2102 · Jun 18, 2020 at 03:08 PM
For people who are trying to do this in 3D space , you just have to do is to change y to z so code will be something like this
public GameObject cube;
void Start()
{
int x, z;
int length = 50;
float angle = 0.0f;
float interval = 0.1f;
while (angle < 2 * Mathf.PI)
{
x = (int)(length * Mathf.Cos (angle));
z = (int)(length * Mathf.Sin (angle));
Instantiate(cube,new Vector3(x,0,z),Quaternion.identity);
angle += interval;
}
base code by SnotE101
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Using noise to generate Cube World like terrain 0 Answers
Grid based water system 0 Answers
Odd discrepancy with EulerAngles (Circular motion, C#) 1 Answer