Help with Recoil for guns

Hi,

I have been trying to get my Main Camera to rotate up when ever the Fire function is called in my shooting script, just how a recoil in any game looks. I have tried multiply tacktics on this but none of them have worked. Any ideas on how when I shoot my gun, get a hold of the Main Camera (Or MouseLook on the Main Camera) and rotate it up by 5 or somthing like that? Any ideas would help. Thanks in advance!

As @syclamoth said, moving the camera may be impossible if it has MouseLook attached. You should “sandwich” an empty object between the player and the camera, and attach MouseLook to this empty object - this would make it possible to shake or do a recoil movement using localEulerAngles. NOTE: If you insert this object, reset the camera position and rotation, then reset this object’s position and rotation!

This is a simple recoil script: attach it to the camera (or directly to the weapon) and call the function Recoil each time you effectively shoot:

var force: float = 2.5; // controls recoil amplitude
var upSpeed: float = 9; // controls smoothing speed
var dnSpeed: float = 20; // how fast the weapon returns to original position

private var ang0: Vector3; // initial angle
private var targetX: float; // unfiltered recoil angle
private var ang = Vector3.zero; // smoothed angle

function Start(){
	ang0 = transform.localEulerAngles; // save original angles
}

function Recoil(){
	targetX += force; // add recoil force
}

function Update(){ // smooth movement a little
	ang.x = Mathf.Lerp(ang.x, targetX, upSpeed * Time.deltaTime);
	transform.localEulerAngles = ang0 - ang; // move the camera or weapon
	targetX = Mathf.Lerp(targetX, 0, dnSpeed * Time.deltaTime); // returns to rest
}

You can call the function Recoil using SendMessage when you call your Fire function. If the script that will call Recoil is in a parent object, use BroadcastMessage(“Recoil”); if it’s in a child, use SendMessageUpwards(“Recoil”).

If you have a ‘mouselook’ component directly on the camera, it won’t really work. However, if you make the camera a child of the mouselook, then you can do some more interesting things.

Now that your camera can move independently of the mouseLook, you can create a ‘ScreenShakeEffects’ controller. On this controller, you can modify ‘transform.localRotation’ to make the camera move offset from the mouselook. You could even use a translation offset for shaking (for explosions or damage etc.).

void mfRecoil(){
transform.localEulerAngles = new Vector3(Random.Range(transform.localEulerAngles.x - 2f, transform.localEulerAngles.x - 3f), Random.Range(transform.localEulerAngles.y - 2f, transform.localEulerAngles.y + 2f), transform.localEulerAngles.z);
}
attach this script to the gameobject that you want recoil on, and call this function for recoil.