Skip to content

Tutorial part 5 : Bullet and Enemy events

ilovethisid edited this page Jun 8, 2021 · 2 revisions

Last time, bullets didn't kill enemies and enemies passed through bullets. This time, we will make bullets and enemies destroy each other. Add the following code to the bottom of collisionEvent().

    for (int j = 0; j < bullets.size(); ) {
        if (bullets[j]->collision_flg) {
            delete bullets[j];
            bullets.erase(bullets.begin() + j);
        }
        else j++;
    }

    for (int j = 0; j < enemys.size();) {
        Enemy* tmp = (Enemy*)enemys[j];
        tmp->event(getConsole());

        if (tmp->type == 0) tmp->shoot(bullet_images[1], enemy_bullets);
        // type 0 is shooting type

        if (tmp->collision_flg) {
            // if on collision, collision_flg = 1
            tmp->life--;
            if ((tmp->life) <= 0) {
                delete tmp;
                enemys.erase(enemys.begin() + j);
            }
            else
                j++;
            tmp->collision_flg = 0;
        }
        else j++;
    }

collision_flg = 1 when collision is true. Then the code means that bullets and enemies are destroyed when on collision.
If you run the game, you can find that a bullet destroys an enemy and gets destroyed.
But, enemy is destroyed when in collision, so enemy is destroyed when player collides with enemy.
That is okay, but since we didn't make any life points for player, player can destroy enemies even without moving.
So, we will make life points for player next time.