0
\$\begingroup\$

I have some trouble to do a Recoil routine. I've a Tank, a turret cannon on it. I want that after shot, turret fast recoil back, than (slowly) get back to start position.

This is the code I've tought but obviously it not works.

Update () {
  if(shot) {
     Shot();
     TurretBackRecoil();
  }

}

private void TurretBackRecoil() {       
   transform.Translate(new Vector3(0,-10,0) * Time.deltaTime * 3 );         
}

private void TurretForwardRecoil () {
    transform.Translate(new Vector3(0,10,0) * Time.deltaTime);
}
\$\endgroup\$
2
  • 2
    \$\begingroup\$ You'd get more control just putting this on an animation timeline - then you can freely tune the sharpness of the recoil and easing on the recovery curve, without obscure math all over. ;) However, if you want to use code to accomplish something over multiple frames, you should read the documentation on Coroutines. \$\endgroup\$
    – DMGregory
    Commented Feb 10, 2017 at 17:20
  • \$\begingroup\$ I would rather suggest a simple physical approach. Calculating a Velocity which increases each shot. Also the Velocity decreases dependent of the current Velocity simply because of friction \$\endgroup\$ Commented Feb 28, 2017 at 0:24

1 Answer 1

1
\$\begingroup\$

The way I have achieved this in the past is to track multiple different recoil variables. These can be changed on the fly, you could have one for visual kick back, one for a targeting offset.

Then, when before drawing the object, set its transformation matrix to be its default transformation plus offsets provided by those variables.

You can then animate those variables in any way you like, such as having it gradually return to 0.

(So if you set recoil=-10; on shoot, it will animate back).

The other benefit of this is that you can easily increase the effect of recoil, or stack the recoil intensity on top of each other by just increasing the variable more.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .