0

I'm having trouble differentiating objects in an array in one of my functions. I created an array that holds 8 enemies

enemy:Enemy;
enemyArray:Array = [];
for (i = 0; i < 8; i++)
{
    enemy = new Enemy();
    enemyArray.push(enemy);
}

Now each of these enemies are different because I assign them different strings. So for example,

enemyElemeny:String;
enemyArray[0].enemyElement = "Water";
enemyArray[1].enemyElement = "Fire";
etc....

Here's the problem. The player does more damage depending on the element of the enemy, however, it does the same damage to all enemies, possibly because I have enemyArray[j] in the if statement.

var j:int;
for (j = 0; j < enemyArray.length; j++)
{
    if (enemyArray[j] != null)
    {
        trace(enemyArray[0].enemyElement, enemyArray[1].enemyElement)
        if (player.playerElement == "Electric")
        {
           if (enemyArray[j].enemyElement == "Water") 
               { 
                     //DO A LOT OF DAMAGE
                     damage = 20
               }
           else if (enemyArray[j].enemyElement == "Fire") 
               {
                      //DONT DO A LOT OF DAMAGE
                      damage = 10 
               }
        }
    }
}

So if I have two enemies on the screen, one water and one fire, it'll do the same damage to both.

1 Answer 1

1

You alter the only variable, named damage, and then you assign that damage to each of the enemies in turn, that's why you do the same damage to all the enemies. Instead, you should apply the damage to one enemy at a time within that loop of yours.

var j:int;
for (j = 0; j < enemyArray.length; j++)
{
if (enemyArray[j] != null)
{
    trace(enemyArray[0].enemyElement, enemyArray[1].enemyElement)
    if (player.playerElement == "Electric")
    {
       if (enemyArray[j].enemyElement == "Water") 
           { 
                 //DO A LOT OF DAMAGE
                 damage = 20
           }
       else if (enemyArray[j].enemyElement == "Fire") 
           {
                  //DONT DO A LOT OF DAMAGE
                  damage = 10 
           }
    }
    // put all the other elements of player&enemy in here
    enemyArray[j].takeDamage(damage); 
    // and then apply the calculated damage to only j'th enemy, not to every enemy
}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. So when you say apply damage to one enemy at a time, would I need to replace the j with the actual numbers, like enemyArray[0], enemyArray[1], etc?
No, your j already iterates through all the array. It's just when you apply damage, you alter only one object at a time, right after you calculate the damage it needs to receive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.