- Home /
Fixed bullet spread
I am making a skill based first person shooter, and for this reason I do not want my weapons to have deviation based on random number generation. Instead, I would like for the shotguns to spread the pellets in a specific pattern each time I fire the gun. Though I can set different values for the raycasts to use, I cannot figure out why the spread pattern changes based on where the player is looking.
As you can see, the bullet spread changes when looking around. Of course, I'd prefer that when you look down with the shotgun, the shotgun also not be turned to the right for whatever reason, as the character seems to be doing.
Using code, how would I stop the above tragedy from happening?
The script is pretty simple thus far, camera rotates with the mouse, press a button and it summons a few raycasts. These raycast's directions change based on the pre-defined angle measures I added.
The combatShotgunAngles array is three vectors, one being vector3.zero, the next being 0, 0.1, 0.1, and the last being the negative version of the latter vector. I'm looking to make that three pellet spread stay consistent no matter where the player is looking.
if (Input.GetKey(KeyCode.Q))
{
for (int i = 0; i < 3; i++)
{
Vector3 direction = transform.forward;
direction.x += combatAngles[i].z;
direction.y += combatAngles[i].y;
direction.z += combatAngles[i].z;
if (Physics.Raycast(transform.position, direction, out RaycastHit testHit))
{
GameObject testObj = GameObject.CreatePrimitive(PrimitiveType.Cube);
testObj.transform.position = testHit.point;
testObj.transform.localScale *= 0.1f;
}
}
}
Edit: I have tried using transform.transformDirection, and I think it may prove helpful, though I am not sure where to place it.
There is also the possiblity I should be using quaternions for the directions and adding angles instead of a normalized array of vector's to each pellet.
My progress on reaching fixed, consistent spread, however, has been minimal.
I believe it has something to do with world space vs local space (position vs local position).
Transform.forward is relative to rotation, that might be affecting it, Vector3.forward is normal z.
Answer by xthunderduckx · Apr 22, 2019 at 10:28 PM
Thanks to the help of the forum and a few members at the Newblood discord server, I was able to figure out that the vectors were missing the z value, which I didn't think was actually a necessity for this kind of thing.
I set all the z values for the spread to 1, and it worked great.