Bart Bartoman
Bart Bartoman

Reputation: 766

Javascript Canvas, can't draw multiple images

For a school project, I need to make a kind of "Invader" game.

Actually, I got some issue with picture drawing. It works for 1 picture, but not for multiple. Also if I try to draw only rectangles, instead of pictures, it doesn't work.

So I guess something is wrong in my code, but I don't know how to find it.

Since my code got multiple libraries, I uploaded it to a server: Link to the project

My script source code for drawing enemies (which draw only one, not all of them):

function moveEnemy(myEnemy, indexEnemy) {
    myEnemy.posY += 1;
    if( myEnemy.posY >= GAME_HEIGHT )
    {
        myEnemy.posX = _.random(0, 600 );
        myEnemy.posY = _.random(0, -1000);
        player.score -= 2;
    }

    // check collision with player
    if (myEnemy.posX < player.posX + player.size && myEnemy.posX + myEnemy.size > player.posX && myEnemy.posY < player.posY + player.size && myEnemy.size + myEnemy.posY > player.posY) {
        loadGame();
    }

    // check collision with bullet
    _.map(tabShot, function(myShot, index) {
        // check collision with shot
        if (myShot && myEnemy.posX < myShot.posX + myShot.sizeX && myEnemy.posX + myEnemy.size > myShot.posX && myEnemy.posY < myShot.posY + myShot.sizeY && myEnemy.size + myEnemy.posY > myShot.posY)
        {
            myEnemy.posX = _.random(0, GAME_WIDTH-myEnemy.size);
            myEnemy.posY = _.random(0, -1000);
            player.score += 3;
            _.pull(tabShot, myShot);
            return true;
        }
        return false;
    });
    // check collision with player
    if (myEnemy.posX < player.posX + player.size && myEnemy.posX + myEnemy.size > player.posX &&
        myEnemy.posY < player.posY + player.size && myEnemy.size + myEnemy.posY > player.posY) {
        loadGame();
    }
    images.enemy.draw(CONTEXT, enemy.posX, enemy.posY);
}

Upvotes: 0

Views: 98

Answers (1)

Niddro
Niddro

Reputation: 1725

The reason for only seeing 1 enemy is becuase you're using the wrong variable to the x and y coordinates. You were using the variable enemy that you used to make the enemies.

Change the last row in your moveEnemy function from

images.enemy.draw(CONTEXT, enemy.posX, enemy.posY);

to

images.enemy.draw(CONTEXT, myEnemy.posX, myEnemy.posY);

Upvotes: 1

Related Questions