Search code examples
c#unity-game-enginequaternionsangle

Spawn bullets in different directions (Unity/C#)


I'm trying to create a half circle bullet spread (similar to the illustration attached IMAGE).

I'm not sure how to properly calculate angles. Right now what I have is a gun that can be aimed in any direction so I'm taking its rotation as a consideration as well. Then the bullet shoots at the direction is pointing at.

Here is the pseudo-code of what I currently have. But now, I don't know how to calculate angles and do a half circle bullet spread with respect to the current direction.

I've looked into tutorials like this but can't understand enough to apply to what I currently have.

intprojectileCount = 5;
Quaternion gunRotation = GetGunGlobalRotation();
 
for (var i = 0; i < projectileCount; i++)
{
     Projectile projectile = Instantiate(projectilePrefab);
     projectile.transform.position = gunBarrelPos;
     projectile.rigidbody.velocity = (gunRotation * Vector3.forward) * speed;
}

I've tried doing something like.

var angleStep = testAngle / projectileCount;
var angle = FP._0;


var direction = gunRotation * Vector3.forward;
var xDir = FPMath.Sin(angle * FP.Deg2Rad);
var zDir = FPMath.Cos(angle * FP.Deg2Rad);
var scatteredDir = new FPVector3(xDir, 0, zDir).Normalized;

direction += scatteredDir;
angle += angleStep;

projectile.rigidbody.velocity = direction * speed;

of course, this isn't working correctly. I've just been doing some trial and error so I'm not sure how to fix it.


Solution

  • I don't really understand the way that you tried to do it, but I would probably do something like that:

    for (int i = 0; i < projectileCount; i++)
    {
        GameObject projectile = Instantiate(projectilePrefab, gunBarrelPos, gunRotation);
        Vector3 scatteredDir = new Vector3(Random.Range(-90,90),Random.Range(-90, 90), Random.Range(-90, 90));
        projectile.transform.Rotate(scatteredDir);
        projectile.GetComponent<Rigidbody>().velocity=projectile.transform.forward*speed;
    }
    

    This code instatiates the projectile with the rotation of the gun and just adds a random rotation to it. Then it makes it go into the direction it is facing and its done.