- Home /
pistol recoil rotation
hey, i been trying to make a gun recoil for my pistol and i have a script attached to my gun model.the script works fine somehow... it rotates on x axis about 15 degree. but as i shoot more and more, the gun rotates less and less until it's rotation becomes absolute zero. i created a GIF to show the issue. http://s6.uplod.ir:182/d/2k22yze74hvhuf6tpwoij6jhvjz43kmq7soreocqgk3u7tb2ezzyi6knvdjshyn7mibngw7g/GIF_20180627_162008.gif and here is the script : public class recoiltesti : MonoBehaviour { Vector3 recoilSmoothDampVelocity; public float recoliEnergy;
public float FireRate;
private float NextTimeToFire = 0f;
public float recoilAngelSmoothDampVelocity;
public Quaternion originalRotationValue; // declare this as a Quaternion
public float rotationResetSpeed = 0.1f;
float recoilAngle;
void Start () {
originalRotationValue = transform.rotation;
}
// Update is called once per frame
void LateUpdate() {
// animate recoil
recoilAngle = Mathf.SmoothDamp(recoilAngle ,0 ,ref recoilAngelSmoothDampVelocity,0.1f);
transform.localEulerAngles = transform.localEulerAngles + -Vector3.forward *recoilAngle;
if (Input.GetButtonDown("Fire1") && Time.time >= NextTimeToFire) {
NextTimeToFire = Time.time + 1f / FireRate;
shoot ();
}
else{
resetRot ();
}}
public void shoot ()
{
recoilAngle += 15;
recoilAngle = Mathf.Clamp (recoilAngle, 0, 25);
}
public void resetRot ()
{
transform.rotation = Quaternion.Lerp (transform.rotation, originalRotationValue, Time.time * rotationResetSpeed);
}
}
Answer by Priyanka-Rajwanshi · Jun 28, 2018 at 03:39 PM
You are using Time.time in your function resetRot. As game progresses, this value becomes large. Thus the gun returns to its original value abruptly. You could use:
transform.rotation = Quaternion.Lerp (transform.rotation, originalRotationValue, (Time.time - initialTime) * rotationResetSpeed);
where initialTime is a float value that can be set in shoot () as
initialTime = Time.time;