Instantiate rotation is not correct, why?

I have a Player that shoots bullets from a gun. Depending on the gun, there are different amounts of bullets. With my Shoot() method I want the instantiated bullets to have a fixed spread each time they shoot.

I tried that with a for loop:

void shoot()
    {
        //Set Spread
        float spread = 10;
        float currentSpread = 0;

        //Instantiate Bullet
        for (int i = 0; i < amount; i++)
        {
            //Get Spread
            if (i == 0)
            {
                currentSpread = 0;
            }
            else if (i == 1)
            {
                currentSpread = spread;
            }
            else if (i == 2)
            {
                currentSpread = -spread;
            }
            else if (i == 3)
            {
                currentSpread = spread * 2;
            }
            else if (i == 4)
            {
                currentSpread = -spread * 2;
            };

            //Instantiate
            Bullet = Instantiate(PreFab, Canvas.position, Quaternion.Euler(0, 0, Player.rotation.y + currentSpread));

            //Set Parent
            Bullet.transform.SetParent(Canvas, false);

            //Set Name
            Bullet.gameObject.name = "TeamBulletOne";
        }
    }

The “Canvas” is where the Bullets (2d) spawn, the rest of the world is 3d.


However, when I shoot it randomly either instantiates the bullets with a slightly off rotation or they spawn with about 2 degrees difference, not with the 10 degrees that are set in the Shoot() position.


I have no idea why and no matter how often I change or go through the method, I can’t find out why it isn’t working…

I don´t have anything else that affects the shooting mechanism, the colliders on my bullets are set to ignore the player and the other bullets and gravity is of as well.


Does anyone have an idea what to do?

You might want to try Quaternion.AngleAxis(player.up, currentSpread);. This will create a rotation around the player y-axis, with a certain degree. You might get weird results because player.rotation.y is the y component of a Quaternion, and Quaternions are 4 dimensional hocus pocus. Its not the same as player.transform.localEulerAngles, which is the rotation you see in the inspector, which you can’t really use because of the rollback to 0 after 360 (or -180, 180 not sure atm).


Also, I wanted to say, instead of using -else if-, you could use -switch- statement. But what would be even better is using the following ternary operator: currentSpread = i % 2 == 0 ? (i / 2) * -spread : (i + 1) / 2 * spread;

It is the same as your if else, but you dont need to rewrite for every i value. (If you are not familiar with the ternary operator: value = condition ? if condition is true : if condition is false. So in this case: currentSpread = i is even ? calculate value for even i : calculate value for odd i. )