- Home /
Proper Recoil for gun?
So I have a working script for recoil, but the thing is, it jumps to the spot then jumps back, Is there any way to make a smooth transition for recoil? So it gradually goes up, rather than just instantly moving up?
#pragma strict
function Start(){
}
var triggerfire : GameObject;
function Recoil(){
transform.Rotate(Vector3.down * Time.deltaTime * 1875);
}
function Recoilreturn(){
transform.Rotate(Vector3.up * Time.deltaTime * 1875);
}
function Update(){
if(Input.GetMouseButtonDown(0) || (Input.GetMouseButtonDown(1)) || (Input.GetMouseButtonDown(2)) || (Input.GetKeyDown (KeyCode.Space))){
Invoke("Recoil", .221);
//triggerfire.animation.Play("fire1");
Invoke("Recoilreturn", .421);
}
}
Comment
There's nothing in this script that does recoil. All this script does is shoot the bullet.
Answer by Griffo · Mar 26, 2013 at 06:55 AM
Try using this, it can be used for smoothly zooming a weapon or you can adapt it to suit your means, alter the Vector3 to move the direction you want and play around with the speed, should point you in the right direction -
#pragma strict
var recoilSpeed : float = 0.01; // Speed to move Gun/Camera/ up and down
function Update () {
if (Input.GetKeyDown ("left ctrl")){
recoilBack();
}
if (Input.GetKeyUp ("left ctrl")){
recoilForward();
}
}
// Move current weapon to zoomed in position smoothly over time
function MoveToPosition(newPosition : Vector3, time : float){
var elapsedTime : float = 0;
var startingPos = transform.position;
while (elapsedTime < time){
transform.position = Vector3.Lerp(startingPos, newPosition, (elapsedTime / time));
elapsedTime += Time.deltaTime;
yield;
}
}
function recoilBack(){
// Start coroutine to move the camera up smoothly over time
var zoomOutOffset = Vector3(0, 0, 0.5);
var zoomOutWorldPosition = transform.TransformDirection( zoomOutOffset );
// Move the camera smoothly
StartCoroutine(MoveToPosition(transform.position + zoomOutWorldPosition, recoilSpeed));
}
function recoilForward(){
// Start coroutine to move the camera down smoothly over time
var zoomInOffset = Vector3(0, 0, -0.5);
var zoomInWorldPosition = transform.TransformDirection( zoomInOffset );
// Move the camera smoothly
StartCoroutine(MoveToPosition(transform.position + zoomInWorldPosition, recoilSpeed));
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613095115im_/https://answers.unity.com/themes/thub/images/avi.jpg)