Reputation: 1625
My problem is that when I try to erase a secefic object in my vector it removes all the object before that object.
I've done this in the Bullet class, can it have something to do with it?:
Bullet operator=(Bullet);
Bullet Bullet::operator=(Bullet b) {
Bullet newBullet(NULL, NULL);
return(newBullet);
}
If I don't have this I get
error C2582: 'operator =' function is unavailable in 'Bullet'
This is where I define each element to the bullets vector:
if (p_shoot) {
bullets.insert(bullets.begin(), Bullet(p_getHitboxX(), p_getHitboxY() + (p_getHitboxH() / 2)));
p_shoot = false;
}
This is the code where it happens:
if (!bullets.empty()) {
for (unsigned int i = 0;i < bullets.size();) {
if (bullets.at(i).bullet_collisionCheck(rect)) {
bullets.erase(bullets.begin() + i);
}
else i++;
}
}
I don't get it why it removes all the Bullet objects before the specific Bullet object in the index I want to erase. It's like it removes all objects between bullets.begin() and i.
Let's say that bullets contains 3 Bullet objects, the first bullet collides making bullet_collisionCheck return true, which means that the index is 0 but then it erases bullets[2] first then bullets[1] and lastly bullets[0] the one i wanted to erase first.
I've been experimenting a bit to see what's going on so I wrote this code to see exactly what happens:
bullets.push_back(Bullet(100, 100));
bullets.push_back(Bullet(200, 200));
bullets.push_back(Bullet(300, 300));
bullets.push_back(Bullet(400, 400));
bullets.push_back(Bullet(500, 500));
bullets.erase(bullets.begin() + 3);
When this code runs, it should remove the Bullet(400, 400) but it removes the last, Bullet(500, 500). I changed the value to 1 which means it should remove Bullet(200, 200) but it still removes the last, Bullet(500, 500). What is going on?
Please help.
Upvotes: 1
Views: 203
Reputation: 1625
I found the solution to the problem, thank you all for your help.
The problem was:
Bullet operator=(Bullet);
Bullet Bullet::operator=(Bullet b) {
Bullet newBullet(NULL, NULL);
return(newBullet);
}
I just had to change it to :
void operator=(const Bullet &b);
void Bullet::operator=(const Bullet &b) {
bullet_hitbox.x = b.bullet_hitbox.x;
bullet_hitbox.y = b.bullet_hitbox.y;
}
Upvotes: 1
Reputation: 1
Adding new objects using "bullets.insert(bullets.begin(),..." is adding new object to the begining, so first created bullet that makes bullet_collisionCheck returning true will be last one (bullets[2]).
I think the condition if (bullets.at(i).bullet_collisionCheck(rect))
causes the problems, because bullets.erase(bullets.begin() + i);
should work fine.
Upvotes: 0
Reputation: 1078
Give this a try: Just using iterating based on iterators and not on indexing.
if(!bullets.empty())
{
for ( auto it = bullets.begin(); it != bullets.end(); ++it )
{
if ( it->bullet_collisionCheck(rect) )
{
it = bullets.erase( it );
--it;
}
}
}
Upvotes: 0