Hello and thank you for reading this and helping me.
I am using SDL and openGL. I want to get my guy to shoot a bullet every time i press "space", or hold down space for rapid fire. I am using vectors to do it. Can someone please just help me and tell me what i should do or how to do it because i tried and i had no idea how to go about it.
I have a main.cpp, a player class and a bullet class. SHould i make a vector or bullet objects? and if so should i declare it in 'main' or 'player.h'?
Then how could i shoot one. like?
if (key pressed == SPACE)
{
'bullet vector'.push_back
}
or do i add a bullet or something?
please can anyone please show me how to do this and what to do. thank you very much!
Make an empty vector of bullets before you start your game loop like so: std::vector<cBULLET> bullets;
Here I am assuming that you've created a bullet class called cBULLET. It would have the associated sprite, a direction, position, maybe velocity, etc. This vector could be a member of your character class so that opponents could also use this without needing to define it again.
In the interface part of your game loop:
1 2 3 4
if (key_pressed == SPACE)
{
bullets.push_back(cBULLET());
}
This creates a new bullet with the default constructor and puts it into the array.
At some point you will want to process your bullets:
1 2
for (std::vector<cBULLET>::iterator it = bullets.begin(); it < bullets.end(); ++it)
*it.process()
This calls the member function process() for each bullet. process() would be part of your cBULLET class and would do things like move the bullet a certain amount since last frame, perhaps do damage (but this may be a better thing to do in the victem's class), and determine whether it should be deleted.
Once a bullet has hit something or gone off the screen or something, you'll want to delete it. In process() we would have driven a flag, let's call it .bFinished.
1 2 3
for (std::vector<cBULLET>::iterator it = bullets.begin(); it < bullets.end(); ++it)
if (*it.bFinished)
bullets.erase(it--);
If the bullets have to diseappear, std::list is more efficient for erasing objects.
If you really want to access at random position(but it sould not be the case), use std::deque instead.
thankyou very much for all the replies. I do not no much about vectors at all, other than how to declare them, add or remove the last element of it. Resize it and get the size of one.
But how would i draw and move a bullet for each vector?
i have a function which draws bullet, and moves the X coordinate of the bullet 1 to the left, then since i called the function in my game loop, it moves it, then redraws it, then moves it then redraws. but how could i keep drawing a nothing bullet and a new bullet for each new element?