Basic weapon recoil

Many other posts i’ve found regarding recoil tend to speak about the kind of recoil seen in games like CoD or Counter-Strike. In my project i would like basic recoil that’ll reset smoothly after a certain period of time, being more similar to the recoil of the 357 magnum in Half-Life. I would like the camera to rotate vertically by a certain ammount and then reset. This then really turns it into more visual feedback than recoil but eh…

Of course i have tried this, but i am a fairly inexperienced programmer and my various attempts break the script.

I am working with JS and with 4 variables:

var mainCamera : Transform ;
var kickAmmount : float = -1 ;
var kickTime : float = 0.1 ; // Time taken for camera to rotate after a shot
var kickResetTime : float = 0.2 ; // Time taken for cameras rotation to reset after a shot

I would appreciate any help. Thanks!

I think you can get away with only one variable and one constant. The amount of current kick (starting at 0) and the speed at which the camera resets. Every time you shoot, add more to the kickAmount and every frame, decrease it by a kickReset constant. Then set the difference to the camera.

I’m not entirely sure on the JavaScript (I use C#), so here’s my best psuedo code:

var mainCamera : Transform;
var kickAmount : float = 0f; // no kick at the start
var kickReset : float = 10.0f; // 10 units a second?  play with this

void Shoot()
{
    kickAmount += 5.0f;
}

void Update()
{
    kickAmount = Mathf.Clamp(kickAmount - kickReset * Time.deltaTime, 0.0f, 90.0f);
    mainCamera.rotation = actualRotation.rotation + kickAmount;
}

You’ll want to store your “actual” rotation separate from the Camera’s rotation otherwise you’ll always be looking more and more up.