Chain lightning attack

I am trying to create a function for a chain lightning attack in a tower defense game and I am unsure of how to prevent the chain attack from bouncing between the two same targets back and forth.

Currently, I am using a collision sphere extending from the first target to get the closest enemy object but using simply this from the second target could potentially cause bouncing behavior. How can I counteract this?

The function is currently being called by a missile object on collision with it’s target. I am writing in JavaScript.

Keep a list of targets you’ve already hit, something like

var hitTargets : List.<GameObject> = List.<GameObject> ();

in your projectile. When you’ve found a target to jump to, see if the target already exists in your list using

hitTargets.Contains (newTarget.gameObject)

If it’s already there, don’t jump to it and find the next target that isn’t already in your list. When you find that target, add it to the jump to it and add it to the list:

hitTargets.Add (newTarget.gameObject);

The whole check might look something like:

var newTarget : Target = FindTarget (currentTarget); //I'm guessing at the name of your target class/interface, and you'd implement finding a target however you like
while (hitTargets.Contains (newTarget.gameObject))
{
    newTarget = FindTarget (currentTarget);
    if (newTarget == null) // Make FindTarget return null or in some way indicate if there are no more targets to jump to so we know to break out if we can't find a target.
    {
        return;
    }
}

// Once we're out of that loop, we know the target hasn't already been hit.
JumpTo (newTarget); //Do whatever you need to do to move the projectile along.
hitTargets.Add (newTarget.gameObject);

Each target has a boolean flag in it, “alreadyHit”. When they get hit, set that true. Further checks ignore any target with that set true. When the whole attack is done, set all of these flags to false.