- Home /
Question by
SaplingGames5 · Mar 04, 2021 at 02:51 PM ·
bulletgun scriptspread
How to make a bullet spread
So I'm making an fps game but I'm having a hard time creating bullet spread. I used brackeys tutorial for shooting but he never showed how to make bullet spread (either that or I'm dumb and didn't listen). here is my shooting script: (and I don't have any spread code on it because nothing has worked)
void Shoot()
{
currentAmmo--;
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
}
}
I hope someone has an answer.
Comment
Answer by unity_ek98vnTRplGj8Q · Mar 04, 2021 at 07:26 PM
Something like this will give you bullet spread in a random circle around your aim line
public float maxSpreadDegrees = 5f;
void Shoot(){
Vector2 spreadDirection = Random.insideUnitCircle.normalized; //Get a random direction for the spread
Vector3 offsetDirection = new Vector3(fpsCam.transform.right.x * spreadDirection.x, fpsCam.transform.up * spreadDirection.y, 0); //Align direction with fps cam direction
float offsetMagnitude = Random.Range(0f, maxSpreadAmount); //Get a random offset amount
offsetMagnitude = Mathf.Tan(offsetMagnitude); //Convert to segment length so we get desired degrees value
Vector3 bulletTrajectory = fpsCam.transform.forward + (offsetDirection * offsetMagnitude); //Add our offset to our forward vector
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, bulletTrajectory, out hit, range))
{
}
}
Your answer
Follow this Question
Related Questions
Spreading Fire (Bullets) 3 Answers
making my gun shoot... 3 Answers
i have too many bullets... 2 Answers
My bullet isn't facing the correct way when I shoot it out of my gun. Help! 0 Answers