Search code examples
c++loopsmultidimensional-arraygame-engine

Space Invaders: All enemies in column die when shot


I am trying to program space invaders in C++ I am not an expert and decided to store the enemies in a multidimensional array.

Here each enemy is a column. The rows are from top to bottom: x, y1,y2,y3,y4,y5 and enemy health. y1 is the lowest row (or the row of enemies closest to the player).

When I currently shoot my bullet at the enemies, the entire row of enemies disappears, but I want just one enemy to disappear per bullet. Can anyone tell me where I went wrong please?

if (keys.fire && bullet.health == 0)
{
    bullet.y = width - spriteSize;
    bullet.x = player.x;

    bullet.dy = 1;
    bullet.dx = 0;
    bullet.health = 1;

}

bullet.y -= bullet.dy;
bullet.x += bullet.dx;

if(bullet.health > 0)
{
    drawSprite(Bullet, bullet.x, bullet.y);
}

for(int i = 0; i < 12; i++)
{
    for(int j = 1; j < 6; j++)
    {
        if(distanceBetween(enemies[0][i], enemies[j][i], bullet.x, bullet.y) < 20)
        {
            enemies[6][i] = 0; //Enemy Health
            enemies[j][i] = -1;
            bullet.health = 0;
        }

        if(enemies[6][i]>0)
        {
            for(int sprite = 1; sprite < 6; sprite++)
            {
                drawSprite(Enemy1, aliens[0][i], aliens[sprite][i]);
            }
        }

Solution

  • You are using common enemy health per each row, so all enemies in a row will die as you says.

    To avoid this, you have to allocate enemy healthes for each enemies.

    possible fix:

    for(int i=0;i<12;i++)
    {
        for(int j=1; j<6; j++)
        {
            if(distanceBetween(enemies[0][i], enemies[j][i], bullet.x, bullet.y)<20)
    
            {
                enemies[5+j][i]=0; //Enemy Health
                enemies[j][i]=-1;
                bullet.health = 0;
    
            }
            if(enemies[5+j][i]>0)
            {
                drawSprite(Enemy1, aliens[0][i], aliens[j][i]);
            }
        }
    }
    

    Now you have to allocate (at least) 11 elements instead of 7 for each row of the array enemies.