2
\$\begingroup\$

How can I shoot a bullet in three-dimensional space in such a way that its path diverges a bit, randomly, from the direction in which the gun is pointed?

I know I have to use the Quaternions, but I don't know how exactly.

Three-dimensional possible directions

Should I convert Quaternion to EulerAngles

Quaternion randomRotation = Random.rotation;    
Vector3 inEuler = randomRotation.eulerAngles;

or is there a fairer / nicer way to do it?

\$\endgroup\$
0

1 Answer 1

5
\$\begingroup\$

Should I convert Quaternion to EulerAngles

No, going to EulerAngles makes most things worse.

Try something like this instead:

Vector3 PickFiringDirection(Vector3 muzzleForward, float spreadRadius) {
    Vector3 candidate = Random.insideUnitSphere * spreadRadius + muzzleForward;
    return candidate.normalized;
}

Here we pick a random vector offset to add to the end of our nominal shooting direction, then normalize it so the result is still a unit vector.

There are more ways to pick a random vector in-line with our shooting direction or only slightly deviating from it than there are to pick a highly perpendicular offset, so this will give a distribution where most shots go toward the middle of the cone, and outliers hitting the edges of the cone are more rare.

Your spreadRadius is roughly the radius of the cone 1 unit from the muzzle, or roughly Mathf.Tan(Mathf.Deg2Rad * angle/2f) where angle is the divergence between opposite sides of the cone.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .