Greetings,
I'm currently engulfing myself into game programming, and so far I've made a pretty stable library for a 2D-side scrolling shooter. Note that I'm not posting this in the game development due to my issue being more general than game-specific.
What I'm experiencing trouble with, is upon deleting an object, more specific, a bullet. Within the game control class (Player), I've got an array of bullet-pointers.
I know I'm doing something wrong, and after countless google searches and endless ways of typing the code, I'm turning for outside help.
The specific errors I'm experiencing is as follows:
- The bullets does not get deleted after reaching 40 frames of existence.
- After reaching 40 frames, the handleBullet function attmepts to delete them, it even prints in the console that it does. However, the bullets do not disappear, and the message is printed for each time through the loop. This persists until the game crashes.
Relatively new to "new" and "delete" within objects, if you didn't get that idea already.
//Edited for lenght and the rest is irrelevant.
class Player
{
public:
void shootBullet();
void handleBullet(int);
private:
Bullet* bullets[10];
int bCounter;
int bMag;
int bTimer;
};
These are the two function definitions declared in the code-snip above.
void Player::shootBullet()
{
if( SDL_GetTicks() - bTimer > 100 )
{
bullets[bCounter] = new Bullet( status, x, y );
bCounter++;
if(bCounter == 10 )
{
bMag++;
bCounter = 0;
}
bTimer = SDL_GetTicks();
}
else
cout<<"Cannot shoot that fast, lol\n";
}
void Player::handleBullet(int i)
{
if( bullets[i] != NULL
&& bullets[i]->status() >= 40 ){ //Status is the age of the bullet.
delete bullets[i]; //Increments by 1 for each frame.
printf("Bullet[%d] deleted.\n", i);
}
}
And a snip from the main function of the Player class ( Player::think() ).
bCounter is the counter of bullets. Upon reaching 10, bMag is increased by 1, and bCounter assigned back to zero. I use two integers for this so I don't attempt to access bullets[1-9] after firing one bullet.
if( bMag == 0 )
{
for( int i=0; i<bCounter; i++)
{
if(bullets[i] != NULL )
bullets[i]->think( screen );
handleBullet(i);
}
}
if( bMag != 0 )
{
for( int i=0; i<10; i++)
{
if( bullets[i] != NULL )
bullets[i]->think( screen );
handleBullet(i); //out of loop
}
}
Any help is appreciated an awful lot.