Does anyone know how to create bullet spread with raycasting?
using UnityEngine;
using System.Collections;
using TMPro;
public class GunScript : MonoBehaviour
{
public float reloadTime = 3f;
public float damage = 10f;
public float range = 100f;
public float impactForce = 10000f;
public float fireRate = 15f;
public int maxAmmo = 100;
public float bulletSpreadAmount = 1f;
private int currentAmmo;
public bool isReloading = false;
public Camera fpsCam;
public TextMeshProUGUI ammoTxt;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
public WeaponSwitcher switchWeapon;
public Animator animator;
private float nextTimeToFire = 0f;
void Start()
{
currentAmmo = maxAmmo;
}
void OnEnable()
{
isReloading = false;
animator.SetBool("isReloading", false);
}
// Update is called once per frame
void Update()
{
if (isReloading)
{
return;
}
if (switchWeapon.isSwitching)
{
return;
}
if (currentAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
ammoTxt.text = gameObject.GetComponent<GunScript>().currentAmmo.ToString();
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
public void Shoot()
{
muzzleFlash.Play();
currentAmmo--;
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
Ragdoll target1 = hit.transform.GetComponent<Ragdoll>();
if (target1 != null)
{
target1.TakeDamage(damage);
}
RagdollNotMoving target2 = hit.transform.GetComponent<RagdollNotMoving>();
if (target2 != null)
{
target2.TakeDamage(damage);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForceAtPosition(fpsCam.transform.forward * impactForce, hit.point);
}
GameObject impaceGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impaceGO, 1f);
}
}
IEnumerator Reload()
{
isReloading = true;
Debug.Log("Reloading...");
animator.SetBool("isReloading", true);
yield return new WaitForSeconds(reloadTime - .25f);
animator.SetBool("isReloading", false);
yield return new WaitForSeconds(.25f);
currentAmmo = maxAmmo;
isReloading = false;
}
}