I can tell I’m on the completely wrong track, as this just spams everywhere. I just need to spawn at a controlled rate while the lmb is held down. thanks
your going to want a cooldown, I have a script that should work.
I added bullet spread in there also.
This example uses raycast, as that’s the most optimal way to do it.
public class MachineGun : MonoBehaviour{
public bool shootEnabled = true;
public GameObject sparksPrefab;
//Bullet Spread
public float CurrentSpreadF = 0.0f;
public float CurrentSpreadFactor = 0.0f;
public float HipFireSFactor = 0.0f;
public float ScopedSFactor = 0.0f;
public float SpreadPerSecond = 0.0f;
public float MaxSpreadFactor = 0.0f;
void Update () {
if (Input.GetButton("Fire1")){
if (shootEnabled == true){
ShootReg();
}
}
void ShootReg (){
Transform trf = transform; // a little optimization
RaycastHit hit = new RaycastHit();
Quaternion hitRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
Transform cam = Camera.main.transform;
Ray ray = new Ray(cam.position, cam.forward);
Vector3 v3T = ray.direction;
v3T.y += Random.Range(-CurrentSpreadF / 2.5f, CurrentSpreadF / 2.5f);
v3T.y += Random.Range(-CurrentSpreadF / 2.5f, CurrentSpreadF / 2.5f);
v3T.z += Random.Range(-CurrentSpreadF / 2.5f, CurrentSpreadF / 2.5f);
ray.direction = v3T;
if(Physics.Raycast (ray, out hit, Distance)){
Quaternion rot= Quaternion.FromToRotation(Vector3.up, hit.normal);
if(hit.collider.rigidbody){
if (sparksPrefab) Instantiate(sparksPrefab, hit.point, rot);
hit.rigidbody.AddForceAtPosition((Damage * 4) * transform.forward , hit.point);
} else {
if (sparksPrefab) Instantiate(sparksPrefab, hit.point, rot);
}
}
StartCoroutine(CoolDown());
}
IEnumerator CoolDown(){
changeEnabled = false;
shootEnabled = false;
yield return new WaitForSeconds(SInterval);
shootEnabled = true;
}
}