Weapon firing animation script (randomly movement)

Hello all,

I am trying to make my weapon animate when it shoots (I don’t mean the bullets but the weapon itself) like call of duty or in this video in this link:

I first attempted to make a function and make just the gun to move, but the weapon behaves very strangely. It moves but it moves back again and forwards and back and on and on but very quickly.

My second attempt was using a Coroutine (because coroutines are not restricted to run in a single frame) and the weapon still has the same behaviour. Below I have my code (apologies if it’s very large):

#pragma strict

var check:int;
var Position_back : GameObject; //the position of the empty object.

var zoom : float = 40.0;
var normal : float = 60.0;
var zoom_if_pressed = false;
var aimGunMovement = false;
var UnAimGunMovement = false;
var WeaponDamage = 10;

var runned_while_aiming = false;
var ShootingPosition:GameObject;
var effect: Transform;
var bulletHoleObject: GameObject;
var delay = 0.08;
var counter = 0.0;

//if weapon shooted (this is to do the animated movement of gun when shooting)
var weaponShooted = false;
var targetPosition = Vector3(0.6, 0.6, 1);
var curTime: float;
var elapsed = 0.0;

var smooth : float = 20.0;

function Start () {
	check = 2;
	curTime = Time.time;
}

function Update () {
	// aiming
	if(!(Input.GetKey("w") && Input.GetKey("left shift"))){
		aim();
		shoot();
	}

	if (check % 2 == 1){
		GetComponentInParent(Camera).fieldOfView = Mathf.Lerp(GetComponentInParent(Camera).fieldOfView,zoom,Time.deltaTime*smooth);

	}
	else if(check % 2 == 0){
		runned_while_aiming = false;
		GetComponentInParent(Camera).fieldOfView = Mathf.Lerp(GetComponentInParent(Camera).fieldOfView,normal,Time.deltaTime*smooth);
	}

	if (Input.GetKey("w") && Input.GetKey("left shift")){
		transform.localRotation= Quaternion.Euler(Vector3(0,-180,-25));
		transform.localPosition =  Vector3(0.17,-0.4,0.92);
		zoom_if_pressed = true;
		if (GetComponentInParent(Camera).fieldOfView < 60){
			GetComponentInParent(Camera).fieldOfView = 60; //returning the zoom back to 60 if it's value has been altered
			check = 2;
		}
	}
	else{
		if (zoom_if_pressed){
			transform.localRotation = Quaternion.Euler(Vector3(0,-90,0));
			transform.localPosition =  Position_back.transform.localPosition;
		}
	}
//	GunMoveWhenFire();
}

function aim(){
	if(Input.GetButtonDown("Fire2") && check % 2 == 0){
		print("Hello");
		transform.Rotate(0,0,0);
		transform.localPosition = Vector3(0,-0.275,0.15);
		zoom_if_pressed = false;
		check = check + 1;
	}
	else if(Input.GetButtonDown("Fire2") && check % 2 == 1){
		print("Hello again");
		transform.Rotate(0,0,0);
		transform.localPosition = Position_back.transform.localPosition;
		check = check + 1;
		zoom_if_pressed = true;
	}
}

function GunAnimateRoutine(){ //Coroutine to make the weapon animate when it fires
	while (Vector3.Distance(Vector3(0.17,-0.275,0.15), Vector3(1,1,1)) > 0.05){ 
		transform.localPosition = Vector3.Lerp(Vector3(0.17,-0.275,0.15), Vector3(1,1,1), Time.deltaTime/10);
		yield null;
	}
}

function shoot(){
	Debug.DrawRay(ShootingPosition.transform.position, ShootingPosition.transform.TransformDirection(Vector3(90,0,0))*1000, Color.green);
	counter = counter + Time.deltaTime;

	if(Input.GetKey(KeyCode.Mouse0) && counter >= delay){
		weaponShooted = true;
		var Shot:RaycastHit;
		var fwd = ShootingPosition.transform.TransformDirection(Vector3(90,0,0));
		Debug.DrawRay(ShootingPosition.transform.position, fwd*1000, Color.green);
		this.GetComponent.<AudioSource>().Play();

		if(Physics.Raycast(ShootingPosition.transform.position, fwd, Shot)){
			var particleClone = Instantiate(effect, Shot.point, Quaternion.FromToRotation(Vector3(0,0,0),Shot.normal));
			Destroy(particleClone.gameObject, 2);
			StartCoroutine(GunAnimateRoutine());
			

			if (!Shot.collider.gameObject.tag == "enemy"){
				var bulletHole = Instantiate(bulletHoleObject, Shot.point, Quaternion.FromToRotation(Vector3.up, Shot.normal));
				Destroy(bulletHole.gameObject, 60);
			}

			Shot.transform.SendMessage("DeductPoints", WeaponDamage, SendMessageOptions.DontRequireReceiver);
		}
		counter = 0;
	}
} 

I have been searching for this for days but unfortunately, I had no luck.
Plus I have 10 days of experience with Unity3D and game development.

I appreciate your support and help!

UPDATE: I am still looking and searching out for a solution.

Corrected and tested

OK Use this script to Animate And add other parts of your script in it (Youll have to merge both scripts)

 #pragma strict

public var Gun:Transform;  //The weopon that needs animations
public var firing:boolean;  //Is the gun Firing? Use Your script to turn this true to start the animation and false to stop it
public var MinVibration:float;//the minimum vibration power
public var MaxVibration:float;//the maximum vibration power
 function start(){
 
  }
function Update(){
   //Get Logic Here
   if(Input.GetKey("space")){
     firing = true;
   }
   else{
     firing = false;  
   }
 }
function FixedUpdate(){
    //Execute Movements here 
   if(firing){
      Animate();//Calls the Animate function
    }
}
function Animate(){
	Gun.eulerAngles = new Vector3(Random.Range(MinVibration,MaxVibration),Random.Range(MinVibration,MaxVibration),Random.Range(MinVibration,MaxVibration));
}

Notes:

I hate Quaternions

I hate For loops

It took me 5 hrs to write this script

Unity scripting API needs updates