Function/loop issue

Apr 2, 2012 at 9:22am
Hey i want to create kind of like a bullet shot in c++ and SDL. I have a method in my player class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void player::bullet()
{

    glBegin(GL_QUADS); //GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_QUADS, GL_TRIANGLES, GL_POLIGON

 glBegin(GL_QUADS); //GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_QUADS, GL_TRIANGLES, GL_POLIGON

glVertex2f(xx1,yy1);
glVertex2f(xx1+w1, yy1);
glVertex2f(xx1+w1,yy1+h1);
glVertex2f(xx1, yy1+h1);
glEnd(); //End drawing
xx1+=0.4;

}

where there is xx1, yy1, h1, and w1, those are my variables for my bullet's location which is set to the location of the player. The method is called in a loop, so when it draws the bullet to the screen, it increase the X (xx1) location by one, then repaints it in the new location which makes the bullet move.
BUT
I want it to keep creating new squares each time i call the function ( press SPACE).
thankyou
Apr 2, 2012 at 9:29am
If you want a scrolling shoot 'em up, a good method for this would be creating a vector of bullets. Each time the player presses space, it will resize the vector; therefore creating a new bullet at the correct point. To avoid creating too large of a vector, erase the bullets that go off of the screen.

Good luck!

EDIT:

You'll need a bullet class for this.
Last edited on Apr 2, 2012 at 9:29am
Apr 2, 2012 at 9:31am
ooooo sweet. thankyou. i have no idea about that or how to do it so i guess ill jsut research it. could you maybe give me a briefing first though? please? :)
Apr 2, 2012 at 9:47am
Sure. :) So basically, create a bullet class with all of the values you need.

After this, create a new vector of your bullet class.

(Be sure to #include <vector> inside of your code!)

Every time the player presses Space bar, resize the vector like so:
1
2
3
4
5
6
7
Bullet b;
b.x = PlayerX;
b.y = PlayerY;
b.w = 16;
b.h = 16; //Or whatever size you want.

bullets.push_back(b);


Then, to make the bullets fly to the right, loop through them like this:

1
2
3
for(int i = 0; i < bullets.size(); i++) {
      bullets[i].x += 0.4;
}


After this, make sure the program isn't handling bullets that are off the screen, add to the for loop I coded above the following code:

1
2
3
4
5
6
7
for(int i = 0; i < bullets.size(); i++) {
     bullets[i].x += 0.4;
     if(bullets[i].x >= SCREEN_WIDTH) {
          bullets.erase(bullets.begin() + i);
     }
     //I usually use 800 x 600 windows, this will vary for you though.
}


You might need to look up a few more vector functions, but that's the basic idea. :)

Good luck, once again!
Apr 2, 2012 at 10:07am
thankyou very much! that helped alot
Apr 2, 2012 at 10:09am
No problem :)
Apr 2, 2012 at 10:15am
sorry but i dont really know where to start or how to decclare a vector. I have never used one before
Apr 2, 2012 at 10:27am
vector<Bullet>bullets;

Google is your friend.
Topic archived. No new replies allowed.