Public Group

SDL2 - Storing bullets in a vector

This topic is 1334 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I'm having trouble with shooting bullets while using a vector. The problem is I can't spawn more than 1 bullet at a time. I don't get this problem with an array but the reason I want to use a vector is because its easier to destroy bullets with it.

This is my code to add a bullet to the vector.

for(unsigned int i = 0; i < bullets.size(); i++)
{
if(shooting)
{
bullets.push_back(Bullet());
bullets[i].exists = true;
if(player == playerTextureRight)
{
bullets[i].box.x = GetPositionX() + 25;
bullets[i].box.y = GetPositionY() + 25;
bullets[i].bulletDirection = 1;
}
else //if player is facing left
{
bullets[i].box.x = GetPositionX() + 50;
bullets[i].box.y = GetPositionY() + 25;
bullets[i].bulletDirection = 0;
}
}
shooting = false;
}


And this is my code to draw the bullets

for(unsigned int i = 0; i < shits.size(); i++)
{
if(bullets[i].exists)
{
bullets[i].DrawBullet(laser, ren, bullets[i].box.x, bullets[i].box.y);
bullets[i].MoveBullet();
}

if(bullets[i].box.x > 1000)
{
bullets.erase(shits.begin() + i);
}
}


Like I said, it only spawns one bullet so if a bullet is going across the screen and I press my shoot button, that bullet will just teleport back to where the player is. If I use the same setup with an array, I can shoot as many bullets as I want.

Just can't figure out why so any help is appreciated.

Share on other sites

Don't know if it's the problem but I would expect only 1 bullet.

loop:
{
if(shooting) create_a_bullet;
shooting = false; // loop through the rest, but shooting is false
}

Also, it's not clear why you loop through the bullets, push_back a new one, then set bullets[0].exists = true.

Edited by Buckeye

Share on other sites

Don't know if it's the problem but I would expect only 1 bullet.

loop:
{
if(shooting) create_a_bullet;
shooting = false; // loop through the rest, but shooting is false
}

Also, it's not clear why you loop through the bullets, push_back a new one, then set bullets[0].exists = true.

Thanks a lot it worked! It was just dumb programming on my part the whole time

Share on other sites

Your update loop is mixing bullets and "shits".

I hate when that happens. Porcelain just doesn't have the ballistic resilience for it...

Share on other sites

Your update loop is mixing bullets and "shits".

I hate when that happens. Porcelain just doesn't have the ballistic resilience for it...

I don't know what you are talking about. But the Great and Mighty Poo approves.

Edited by Tangletail

• 22
• 10
• 19
• 15
• 14
×

Important Information

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!