문제

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.

도움이 되었습니까?

해결책

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
}
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top