Problem: The turret I’ve created keeps aiming and firing at the next new target. When a set of enemies come through the collider, it fires at the first one to come through, then aims for the second one as soon as it comes through.
This is the script I’ve created from the turret:
#pragma strict
var myProjectile : GameObject;
var reloadTime : float = 1f;
var turnSpeed : float = 5f;
var firePauseTime : float = .25f;
var muzzleEffect : GameObject;
var myTarget : Transform;
var muzzlePosition : Transform[];
var turretBall : Transform;
private var nextFireTime : float;
private var nextMoveTime : float;
private var desiredRotation : Quaternion;
function Start () {
}
function Update () {
if(myTarget)
{
if(Time.time >= nextMoveTime)
{
CalculateAimPosition(myTarget.position);
turretBall.rotation = Quaternion.Lerp(turretBall.rotation, desiredRotation, Time.deltaTime*turnSpeed);
}
if(Time.time >= nextFireTime)
{
FireProjectile();
}
}
}
function OnTriggerEnter(other : Collider)
{
if(other.gameObject.tag == "Enemy")
{
nextFireTime = Time.time+(reloadTime*.5);
myTarget = other.gameObject.transform;
}
}
function OnTriggerExit(other : Collider)
{
if(other == myTarget)
{
myTarget = null;
}
if(other == myProjectile)
{
Destroy(myProjectile);
}
}
function CalculateAimPosition(targetPos : Vector3)
{
desiredRotation = Quaternion.LookRotation(myTarget.position - turretBall.position);
}
function FireProjectile()
{
nextFireTime = Time.time+reloadTime;
nextMoveTime = Time.time+firePauseTime;
for(theMuzzlePos in muzzlePosition)
{
var newBall = Instantiate(myProjectile, theMuzzlePos.position, theMuzzlePos.rotation);
newBall.GetComponent(CannonBallScript).myTarget = myTarget;
Instantiate(muzzleEffect, theMuzzlePos.position, theMuzzlePos.rotation);
}
}