- Home /
Perfect bullet spread for top-down shooter
I am trying to create a player ability where they can shoot multiple bullets at a time, and I would like them to have a perfect spread. I have tried many things, but the closest I could get wasn't exactly perfect. As can be seen in this screenshot:
In order to accomplish this, I made every odd-numbered bullet move the other way - but it just mirrors the bullet trajectory if it had been on the right side.
This is the code I used:
GameObject FireBullet(GameObject bullet)
{
if (bullet && gunMuzzle)
{
GameObject obj = (GameObject)Instantiate(bullet, gunMuzzle.transform.position, gunMuzzle.transform.rotation);
Physics.IgnoreCollision(gameObject.collider, obj.collider);
return obj;
}
else
{
Debug.Log("Missing bullet prefab and/or muzzle transform!");
return null;
}
}
void FireBullet(GameObject bullet, int amount, float spreadAngle)
{
for (int i = 0; i < amount; i++)
{
float dir = 1;
if (i % 2 == 0) //Checks if number is even
dir = -1f;
GameObject obj = FireBullet(bullet);
obj.transform.Rotate(Vector3.up, spreadAngle * i * dir);
}
}
How can I make a perfect and symmetrical bullet spread?
Answer by VesuvianPrime · Dec 19, 2014 at 02:25 AM
void FireBullet(GameObject bullet, int amount, float spreadAngle)
{
// Todo - need a special case for when amount is 1
float perBulletAngle = spreadAngle / (amount - 1);
for (int i = 0; i < amount; i++)
{
GameObject obj = FireBullet(bullet);
obj.transform.Rotate(Vector3.up, i * perBulletAngle);
}
}
Thanks for your answer, but this doesn't work the way I need it to. Your code here make all the bullets spread out to the right of the first bullet, but I need them to spread out on both sides (without having the issue shown in the picture).
Ok, I misunderstood the original problem, lets try this:
void FireBullet(GameObject bullet, int amount, float spreadAngle)
{
// Todo - need a special case for when amount is 1
float perBulletAngle = spreadAngle / (amount - 1);
float startAngle = spreadAngle * -0.5f;
for (int i = 0; i < amount; i++)
{
GameObject obj = FireBullet(bullet);
obj.transform.Rotate(Vector3.up, startAngle + i * perBulletAngle);
}
}
Your answer
Follow this Question
Related Questions
Spreading Fire (Bullets) 3 Answers
Shoot at an angle 2D 2 Answers
Float to angle coordinate? 1 Answer
How to make a bullet spread 1 Answer
Randomly instantiate bullets within a certain angle based on look direction 1 Answer