Hello,
I am attempting to simulate “recoil” on three similar cannon objects on a tank turret via code (a simple slide back and forth behavior), and I’m having trouble with the side cannons behavior. I am using the Lerp function to move the cannons back and forth. The middle cannon exhibits the behavior I need, however the other two “side cannons” actually move inwards towards the middle cannon, instead of straight back like I want them to, and I’m not sure why.
All cannons have the same exact script which I will post below. And again, the middle cannon works great. It’s the two side cannons that for some reason lerp inwards towards the center. Is there a reason for this? I have a feeling the fact that the tank turret rotates may have something to do with it, but I’m not sure. Thanks for any help.
UnityEngine;
using System.Collections;
public class CannonRecoil1 : MonoBehaviour {
private Transform thisTransform;
public bool shouldRecoil = false;
private bool shouldReturn = false;
private Vector3 startingPosition;
private bool doOnce1 = true;
private bool doOnce2 = true;
private bool doOnce3 = true;
private Vector3 localDirection;
// Use this for initialization
void Start () {
thisTransform = GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
if (shouldRecoil)
{
if (shouldReturn == false)
{
if (doOnce1)
{
startingPosition = thisTransform.localPosition;
//Get the local forward direction
localDirection = thisTransform.InverseTransformDirection(thisTransform.forward);
doOnce1 = false;
}
thisTransform.localPosition = Vector3.Lerp(thisTransform.localPosition, -(localDirection * 0.3f), 0.7f * Time.deltaTime * 10.0f);
if (doOnce2)
{
StartCoroutine("ReturnCannonToOriginalState");
doOnce2 = false;
}
}
else if (shouldReturn)
{
thisTransform.localPosition = Vector3.Lerp(thisTransform.localPosition, startingPosition, 1.0f * Time.deltaTime * 2.0f);
if (doOnce3)
{
StartCoroutine("StopRecoil");
doOnce3 = false;
}
}
}
}
//----------------- FUNCTIONS ----------------------------------------------
IEnumerator ReturnCannonToOriginalState()
{
yield return new WaitForSeconds(0.7f);
shouldReturn = true;
}
IEnumerator StopRecoil()
{
yield return new WaitForSeconds(3.0f);
shouldRecoil = false;
//Allow cannon to recoil again on next attack
shouldReturn = false;
doOnce1 = true;
doOnce2 = true;
doOnce3 = true;
}
}