Raycast bullet spread horizontally only?

How do I go about creating bullet spread in a horizontal line (similar to the Blundergat from Cod BO2 Zombies: Mob of the Dead)?

This is my current code, when I add my horizontal spread value (horSpread) to viewPort.x it works fine but only when facing certain directions. How do I make it work when facing all directions?

for (int i = 0; i < projectilesPerShot; i++)
            {
                float spread = 2;
                Vector3 viewPort;
                float horSpread;

                viewPort = Camera.main.transform.forward;
                viewPort.x += Random.Range(-spread, spread) + horSpread;
                viewPort.y += Random.Range(-spread, spread);
                viewPort.z += Random.Range(-spread, spread);

                RaycastHit hit;

                if (Physics.Raycast(Camera.main.transform.position, viewPort, out hit, 1000))
                {
                    hitPoint = hit.point;
                }
            }

After you get your viewPort value, make an offset variable:

Vector3 offset = Vector3.zero;

Now assign your x, y, z components as you did above, but assign it instead to the offset.

Finally when you go to add the spread back to viewPort, do this instead:

viewPort += Camera.main.transform.rotation * offset;

That will take the offset and rotate it to face as if it was “down +Z” of the camera.

Now in your example, it will only add a constant slew to one site, not a lateral scattering. If you want the lateral scattering (say to make a wide flat target area), just increase the “spread” term that you use for the x component while leaving the others as they are now. Obviously, still use the rotate code I posted above so that it aligns to camera facing.

Also, keep in mind that transform.forward is a unit vector (0,0,1), and you are adding +2 horizontal spread, so that becomes (2,0,1) which is REALLY laterally skewed. Not sure if that’s what you want.

2 Likes

Works perfectly! Thank you very much!!

1 Like