- Home /
Instantiate an image, equally in a circle and rotate it away from the center?
I want to create bullets around the gun so that they are in a circle. And rotate them away from the gun. I can do this manually but I want it to be automatically done by code.
And the order of the bullets has to start from the top and go to the right.
I appreciate any help I can get.
This is what it looks like manually
Answer by SovietAlex · Jul 30, 2018 at 03:57 AM
I figured it out myself. Here is the code if anyone ever needs it in the future.
float totalBullets = 30; //Total Images To Create
float radius = 50; //How Far The Image should be away from the center
Transform CenterPos = GunImage.transform; //The Center Position"
for (int i = 0; i < totalBullets; i++)
{
float point = i / totalBullets;
float angle = (point * Mathf.PI * 2);
float x = Mathf.Sin(angle) * radius;
float y = Mathf.Cos(angle) * radius;
Vector3 pos = new Vector3(x, y, 0) + CenterPos.position;
Image myImage = Instantiate(BulletImage, pos, Quaternion.Euler(0, 0, -Mathf.Rad2Deg * angle, CenterPos);
}
And then if you need to change the size of the image through code you can use this
myImage.rectTransform.sizeDelta = new Vector2("Width", "Height");
And if you want to drag and drop the Image into the Inspector. You have to create a Prefab that has an Image Component and then you have to select the image you want in the prefab.
Answer by toddisarockstar · Jul 27, 2018 at 03:16 AM
the easiest way i can think of is to use a parent object in the center
GameObject pivot;
GameObject [] bullets;
float space;
int amount;
void Start () {
amount = 12;
space = (float)360 / (float)amount;
pivot = new GameObject ();
bullets = new GameObject[amount];
int i = amount;
while(i>0){i--;
bullets[i] = GameObject.CreatePrimitive(PrimitiveType.Cube);
bullets[i].transform.position = new Vector3(pivot.transform.position.x,
pivot.transform.position.y+6,
pivot.transform.position.z);
bullets[i].transform.parent = pivot.transform;
pivot.transform.Rotate(0,0,space);
}}
I would like to ask why the script worked with "while(i>0)" and not when I do "for (i;i>0;i--)"?
you should be able to do the same with a for loop. Sorry, ive just been using "while" a lot lately for other reasons. just replace line 12 with :
for ( i = 0; i < amount; i++){
Your answer
Follow this Question
Related Questions
Objects rotator (rotate objects around a circle) 2 Answers
Rotate a Canvas element over time 0 Answers
Clone positioning inside loop 1 Answer