Simple weapon recoil script

For those who have been searching for a simple method for weapon recoil.

  1. Attach empty game object to the recoilMod transform;
  2. Attach weapon game object
  3. Set maxRecoil (This current setup assumes your rotating on the X axis)
  4. Change recoilSpeed to suit (currently it is set to return to original rotation at half recoilSpeed)
var recoilMod : Transform;
var weapon : GameObject;
var maxRecoil_x : float = -20;
var recoilSpeed : float = 10;
var recoil : float = 0.0;

function Update() {
	if(Input.GetMouseButtonDown(0))
	{
		//every time you fire a bullet, add to the recoil.. of course you can probably set a max recoil etc..
		recoil+= 0.1;
	}

	recoiling();
}

function recoiling() {
	if(recoil > 0)
	{
		var maxRecoil = Quaternion.Euler (maxRecoil_x, 0, 0);
		// Dampen towards the target rotation
		recoilMod.rotation = Quaternion.Slerp(recoilMod.rotation, maxRecoil, Time.deltaTime * recoilSpeed);
		weapon.transform.localEulerAngles.x = recoilMod.localEulerAngles.x;
		recoil -= Time.deltaTime;
	}
	else
	{
		recoil = 0;
		var minRecoil = Quaternion.Euler (0, 0, 0);
		// Dampen towards the target rotation
		recoilMod.rotation = Quaternion.Slerp(recoilMod.rotation, minRecoil,Time.deltaTime * recoilSpeed / 2);
		weapon.transform.localEulerAngles.x = recoilMod.localEulerAngles.x;
	}
}

Thanks for the script, but I get a “BCE0005: Unknown identifier: ‘recoil’.” error:)

Sorry, the script was extracted from a more complete script, missed the variable declaration for recoil.
Recoil just starts at 0, and every shot adds to the recoil time. As long as there is recoil time, the gun will keep recoiling upwards.

var recoil : float = 0.0;

THHHHHAAAAAAAAANXXXXXXXXX a gazzilion

UnassignedReferenceException: The variable recoilMod of ‘Recoil’ has not been assigned.
You probably need to assign the recoilMod variable of the Recoil script in the inspector.
UnityEngine.Transform.get_rotation () (at E:/BuildAgent/work/71ca6fec1b41cc30/Runtime/Export/Generated/BaseClass.cs:805)
Recoil.recoiling () (at Assets/Recoil.js:22)
Recoil.Update () (at Assets/Recoil.js:14)

Thanks for your help! I’ve adapted your code to fit my needs. Maybe someone will benefit from it also.

Create an empty game object and parent it to your character controller, then parent your FPS camera to the empty game object and finally attach the script bellow to your empty game object (recoil controller).

using UnityEngine;
using System.Collections;

public class Recoil : MonoBehaviour
{
	private float recoil = 0.0f;
	private float maxRecoil_x = -20f;
	private float maxRecoil_y = 20f;
	private float recoilSpeed = 2f;

	public void StartRecoil (float recoilParam, float maxRecoil_xParam, float recoilSpeedParam)
	{
		// in seconds
		recoil = recoilParam;
		maxRecoil_x = maxRecoil_xParam;
		recoilSpeed = recoilSpeedParam;
		maxRecoil_y = Random.Range(-maxRecoil_xParam, maxRecoil_xParam);
	}

	void recoiling ()
	{
		if (recoil > 0f) {
			Quaternion maxRecoil = Quaternion.Euler (maxRecoil_x, maxRecoil_y, 0f);
			// Dampen towards the target rotation
			transform.localRotation = Quaternion.Slerp (transform.localRotation, maxRecoil, Time.deltaTime * recoilSpeed);
			recoil -= Time.deltaTime;
		} else {
			recoil = 0f;
			// Dampen towards the target rotation
			transform.localRotation = Quaternion.Slerp (transform.localRotation, Quaternion.identity, Time.deltaTime * recoilSpeed / 2);
		}
	}

	// Update is called once per frame
	void Update ()
	{
		recoiling ();
	}
}

From your gun script when a shot is triggered call the Recoil script this way:

void Start ()
	{
		cam = GameObject.FindWithTag ("MainCamera").transform;
		recoilComponent = cam.parent.GetComponent<Recoil>();
	}

IEnumerator Fire ()
	{
		recoilComponent.StartRecoil(0.2f, 10f, 10f);
                // other firing code;
        }
7 Likes

Is it possible to loop it so that when i’m holding down the mouse button the gun continues to recoil? THANKS A TOOON!!!

This script works except my gun recoils sideways!? How do i change the script so it goes upwards?
I know i have to change x to y but x to y on what??
Ive tried changing
var maxRecoil = Quaternion.Euler (maxRecoil_x, 0, 0);
to
var maxRecoil = Quaternion.Euler (0, maxRecoil_x, 0);
but then NoTHING happens
pls help thanks!

It actually works but for some reason the gun keeps pointing at the same direction even when I turn the camera around.
It’s always aiming at the same spot. Any solution?

Its a bit late but I’ll add my script for others. I added rotation recoil around x and y and a translation recoil for x and z.
Add a parent empty GameObject (Call it Recoil) to your gun and add a reference to that GameObject (Recoil) to your shooting code and add this line (RecoildObject.recoild += 0.1f):

public class LaserGun : MonoBehaviour {

    public Recoil RecoilObject;

    // Update is called once per frame
    void Update ()
    {      
        if (Input.GetButtonDown("Fire1"))
        {
            

            RecoilObject.recoil += 0.1f;
        }
    }

}

Attach this script to the Recoil GameObject:

public class Recoil : MonoBehaviour {

    //public GameObject Weapon;
    public float maxRecoil_x = -20.0f;
    public float maxRecoil_y = -10.0f;

    public float maxTrans_x = 1.0f;
    public float maxTrans_z = -1.0f;

    public float recoilSpeed = 10.0f;
    public float recoil = 0.0f;

    void Update()
    {
        if (recoil > 0)
        {
            var maxRecoil = Quaternion.Euler(
                Random.Range(transform.localRotation.x, maxRecoil_x),
                Random.Range(transform.localRotation.y, maxRecoil_y),
                transform.localRotation.z);
       
            // Dampen towards the target rotation
            transform.localRotation = Quaternion.Slerp(transform.localRotation, maxRecoil, Time.deltaTime * recoilSpeed);

            var maxTranslation = new Vector3(
                Random.Range(transform.localPosition.x, maxTrans_x),
                transform.localPosition.y,
                Random.Range(transform.localPosition.z, maxTrans_z));

            transform.localPosition = Vector3.Slerp(transform.localPosition, maxTranslation, Time.deltaTime * recoilSpeed);

            recoil -= Time.deltaTime;
        }
        else
        {
            recoil = 0;
            var minRecoil = Quaternion.Euler(
                Random.Range(0, transform.localRotation.x),
                Random.Range(0, transform.localRotation.y),
                transform.localRotation.z);

            // Dampen towards the target rotation
            transform.localRotation = Quaternion.Slerp(transform.localRotation, minRecoil, Time.deltaTime * recoilSpeed / 2);

            var minTranslation = new Vector3(
                Random.Range(0, transform.localPosition.x),
                transform.localPosition.y,
                Random.Range(0, transform.localPosition.z));

            transform.localPosition = Vector3.Slerp(transform.localPosition, minTranslation, Time.deltaTime * recoilSpeed);
        }
    }
}

This is how the scene should look like:
3556559--286311--upload_2018-7-7_21-46-21.png

Hope it helps!

1 Like

Works great, even in 2020 :slight_smile: I made the three recoil parameters public variables and added a “hasRecoil” boolean. I also changed maxRecoil_xParam to a negative so the barrel raises vs lowers. Now I can adjust recoil on the fly via the inspector and can change then via script. Thanks!!

1 Like

All you have to do is “getkeydown” so you can hold the click

(10,12): error CS0246: The type or namespace name ‘Recoil’ could not be found (are you missing a using directive or an assembly reference?) help

Please stop necro-replying to 11-year-old posts.

You’ve clearly made a typo somewhere so go back over your work, or else start with a new tutorial.

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Tutorials are a GREAT idea. Tutorials should be used this way:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.
Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

1 Like

Please check dates before replying to threads. Closing.