BennettLiam
BennettLiam

Reputation: 62

How to shoot at the enemy that is farest forward?

Okay so this has been bugging me all day so I thought I would post it here. This is such a specific topic that it was basically impossible to find any sort of references on how this would be done.

for (var i:int=0; i<=Main.bloonList.length-1; i++)
{
    //loop through the children in enemyHolder
    var cEnemy = Main.bloonList[i];//define a movieclip that will hold the current child
    //this simple formula with get us the distance of the current enemy
    if (Math.sqrt(Math.pow(cEnemy.y - this.y,2) + Math.pow(cEnemy.x - this.x,2)) < 100)
    {
        shoot(cEnemy);
        timer = 0;
    }
}

This is the code i have at the moment and i would like to know how to figure out which enemy is the farest along the track. I can find it by using this.

function onEnter(e:Event)
{
    distanceTravelled=distanceTravelled+xSpeed+Yspeed
}

But how can I tell the for loop to target the one with the highest value?

Upvotes: 0

Views: 48

Answers (2)

Sully
Sully

Reputation: 14943

Keep track of the furthest enemy after looping all enemies. At the end shoot.

pseudocode

var maxDistance = 0; 
var furthesEnemy = null;
var currentDistance = null;

for (var i:int=0; i<=Main.bloonList.length-1; i++) {

    //loop through the children in enemyHolder
    var cEnemy = Main.bloonList[i];

    //this simple formula with get us the distance of the current enemy
    currentDistance = Math.sqrt(Math.pow(cEnemy.y - this.y,2) + Math.pow(cEnemy.x - this.x,2));

    if (currentDistance > maxDistance) {
        maxdistance = currentDistance;
        furthesEnemy = cEnemy;
    }
}

shoot(furthesEnemy);

Upvotes: 1

Martin Dinov
Martin Dinov

Reputation: 8825

Just find the highest distance value by updating a new variable (say for example highestDistEnemy) inside your current for loop. You initialize the variable with the first enemy MovieClip object, and only update it to a new enemy object when that enemy's distance is greater than the previous highestDistEnemy's distance. In code:

if(distance(curEnemyDistance) > distance(highestDistEnemy)) {
   highestDistEnemy = curEnemy;
}

where distance just calculates distance as you're already calculating it and initialize highestDistEnemy to Main.bloonList[0] at the start of the loop.

Upvotes: 2

Related Questions