I am building a C++ game using SDL2. Everything was going well and I was able to make the player shoot a single bullet. I later modified my code to render multiple bullets as shown below.
Main game loop
void Game::gameLoop(){
Entity player;
Entity bulletHead;
Entity *bulletTail = new Entity();
bulletTail = &bulletHead;
player.x = 500;
player.y = 640;
player.dx = 0;
player.dy = 0;
player.texture = loadTexture((char*)"res/images/player.png");
SDL_QueryTexture(player.texture, NULL, NULL, &player.w, &player.h);
SDL_Texture *bulletTexture = loadTexture((char*)"res/images/bullet.png");
while(gameState != GameState::EXIT){
prepareScene(); // sets up rendering
handleEvents(); // collects and precesses user input
player.x += player.dx;
player.y += player.dy;
// Player key input
if(player.reload > 0) player.reload--;
if (up)
{
player.y -= 4;
}
if (down)
{
player.y += 4;
}
if (left)
{
player.x -= 4;
}
if (right)
{
player.x += 4;
}
// allow fire bullet every 8 frames
if(fire && player.reload == 0){
player.reload = 8;
// Create bullet
Entity *bullet = new Entity();
memset(bullet, 0, sizeof(Entity));
bulletTail->next = bullet;
bulletTail = bullet;
bullet->x = player.x + 8;
bullet->y = player.y;
bullet->dx = 0;
bullet->dy = -PLAYER_BULLET_SPEED;
bullet->health = 1;
bullet->texture = bulletTexture;
SDL_QueryTexture(bullet->texture, NULL, NULL, &bullet->w, &bullet->h);
}
// handle physics and render for each bullet
Entity *b = new Entity();
Entity *prev = new Entity();
prev = &bulletHead;
// Error starts here
for (b = bulletHead.next ; b != NULL ; b = b->next){
b->x += b->dx;
b->y += b->dy;
blit(b->texture, b->x, b->y);
if(b->y < 0){
if (b == bulletTail)
{
bulletTail = prev;
}
prev->next = b->next;
free(b);
b = prev;
}
prev = b;
}
// Error stops here
blit(player.texture, player.x, player.y); // display image
presentScene(); // displays scene
SDL_Delay(16); // limits fps to around 62fps
}
SDL_DestroyWindow(window);
SDL_Quit();
}
As can be seen above, I can successfully create bullets but whenever I include the for loop to go through my linked list of bullets and move/draw them, the program closes unexpectedly. No error is shown, it just closes as soon as I ran it. Removing the for loop works but I need a way to loop through the linked list of bullets and draw/animate them.