When you see a tank gun firing (Or any sort of big gun) The barrel of the gun is kicked back by the recoil when fired, then slowly moves back into place.
All I need is for the gun (gameobject) is to move back a certain distence at a certain speed (gunKickback) then there needs to be a slight delay (about 0.5 secs)
before the gun moves slowly back into position at a slow speed.
My Script.
using UnityEngine;
using System.Collections;
public class GunController : MonoBehaviour {
int gunKickback = 50;
int gunPulse = 10;
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Jump"))
{
//Gun Kickback/Recoil
transform.Translate(- gunKickback * Time.deltaTime, 0, 0);
//Gun moves back into position
transform.Translate(gunPulse * Time.deltaTime, 0, 0);
}
}
}
Try that code :
using UnityEngine;
using System.Collections;
public class GunController : MonoBehaviour {
int gunKickback = 50;
int gunPulse = 10;
float gunBackDistance; // movement amplitude
private Vector3 originalPosition;
private float updatedTime;
private bool animating = false;
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Jump"))
{
updatedTime = 0;
animating = true;
originalPosition = this.transform.position;
}
if(animating)
{
updatedTime += Time.deltaTime;
// we know the speed and the distance, we can calculate the time of animation
if(updatedTime < gunBackDistance / gunKickback){
transform.Translate(- gunKickback * Time.deltaTime, 0, 0);
}
// second step of the animation
else if(updatedTime >= gunBackDistance / gunKickback + 0.5f){
if(updatedTime >= gunBackDistance / gunKickback + 0.5f + gunBackDistance / gunPulse){
this.transform.position = originalPosition; // to go back to the very accurate original position
animating = false;
} else{
transform.Translate(gunPulse * Time.deltaTime, 0, 0);
}
}
}
}
}
You have to keyed the movement amplitude. All the code is based on animation duration (time to kick back + waiting time of 0.5 + time to move back).
I have not tried this code (not currently on my personal computer) but this should do what you expect.
You will have to manage the case the player press (“Jump”) while the animation is running !!! Without that, you will get a strange behaviour. You may add “&& !animating” to your test “if (Input.GetButtonDown (“Jump”)”.
Hope it helps !