- Home /
C# Gun Recoil Help
I wanted some help to figure out how to add some recoil when a gun is fired. Here is my script. Just move the camera up a bit, but it has a limit to how far up it can do. Not sure if it would need to grab the main camera gameObject to tell it to move up. Any help is appreciated.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Gun_Script : MonoBehaviour {
public float damage = 10f;
public float range = 100f;
public float impactForce = 100f;
public float fireRate = 15f;
public int maxAmmo = 10;
private int currentAmmo;
public float reloadTime = 1f;
private bool isReloading = false;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
public ParticleSystem reloadSteam;
public Text maxAmmoUI;
public Text currentAmmoUI;
private float nextTimeToFire = 0f;
void Start ()
{
currentAmmo = maxAmmo;
maxAmmoUI.text = maxAmmo.ToString ();
currentAmmoUI.text = currentAmmo.ToString ();
}
void OnEnable () {
isReloading = false;
reloadSteam.Stop ();
}
// Update is called once per frame
void Update () {
if (isReloading)
return;
if (currentAmmo <= 0) {
StartCoroutine(Reload());
return;
}
if (maxAmmoUI != null) {
maxAmmoUI.text = maxAmmo.ToString ();
}
if (currentAmmoUI != null) {
currentAmmoUI.text = currentAmmo.ToString ();
}
if (Input.GetButton ("Fire1") && Time.time >=nextTimeToFire) {
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
if (Input.GetButtonDown ("Reload")) {
if (isReloading != true)
{
if (currentAmmo != 0)
{
if (currentAmmo != maxAmmo)
{
StartCoroutine (Reload ());
return;
}
}
}
}
}
IEnumerator Reload ()
{
isReloading = true;
reloadSteam.Play();
yield return new WaitForSeconds (reloadTime);
reloadSteam.Stop();
currentAmmo = maxAmmo;
isReloading = false;
}
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);
}
GameObject impactGO = Instantiate (impactEffect, hit.point, Quaternion.LookRotation (hit.normal));
Destroy (impactGO, 2f);
}
}
}
Comment