My goal was to write a simple space shooter game in a couple of days. Well after about an hour or so of programming, I tested my code and found an ugly bug. I''m storing all bullets in a vector, and everything works fine until I remove the last bullet from the vector, which causes my game to crash.
Here''s my code for adding a bullet:
bullet->v_pos.x = player->v_pos.x + player->size_x / 2;
bullet->v_pos.y = player->v_pos.y + player->size_y / 2;
bullet->v_pos.z = player->v_pos.z - player->size_z;
bullet->alive = true;
bullet->v_vel.y = 1;
BulletList.push_back(*bullet);
and here is my code for loopinh through the vector, updating bullets and checking for collision:
// traverse list of enemies
for(list<CEnemy>::iterator e_it = EnemyList.begin(); e_it != EnemyList.end(); e_it++) {
// traverse list of bullets
for(list<CBullet>::iterator b_it = BulletList.begin(); b_it != BulletList.end(); ++b_it) {
//if bullet is alive, check for collision
if(b_it->alive) {
// check for collision between bullet and enemy
if(Collision(b_it, e_it)) {
// reset enemy
e_it->Reset();
// kill bullet
b_it->alive = false;
// add score
score += 3;
}
if(b_it->alive == false) {
// remove from list
b_it = BulletList.erase(b_it);
}
}
else { // remove from list
b_it = BulletList.erase(b_it);
}
//}
}
thanks for your suggestions...