I'm trying as a personal project to build a Space Invaders clone in C++. Right now, I'm having major issues with Segmentation Faults with my code.
What I'm trying to accomplish is create a vector of Bullet objects that the player fires. Each time the mouse is clicked, the spawnBullet method is called, which creates a new bullet, and adds this to the vector.
I'm not having any luck, here's a snippet of the Game class, which is designed to handle the game logic.
The difficulty in solving this is the fact that the program behaves differently each time it's run. Sometimes it will segfault on launch, sometimes after the mouse has been clicked twice or two minutes down the track and 20+ shots later.
Just wanted to try and get some more experience eyes on this code and see what really is happening.
What I'm trying to accomplish is create a vector of Bullet objects that the player fires. Each time the mouse is clicked, the spawnBullet method is called, which creates a new bullet, and adds this to the vector.
I'm not having any luck, here's a snippet of the Game class, which is designed to handle the game logic.
PHP:
/
#include "Game.h"
Game::Game() {
std::vector<Bullet> shots;
shots.push_back(Bullet(-10, 0, 0));
//resetMatrix(3,8);
}
void Game::moveLeft() {
if (p.getX() > 10)
p.move(-10);
else
p.setX(10);
}
void Game::moveRight() {
if (p.getX() < WIDTH - 10)
p.move(+10);
else
p.setX(WIDTH - 10);
}
void Game::moveTo(int location) {
p.setX(location);
}
void Game::spawnBullet() {
//This needs to be adjusted depending on playermodel.
//Bullet newBullet = Bullet(p.getX(), HEIGHT - 50);
shots.push_back(Bullet(p.getX(), HEIGHT - 50));
}
void Game::process() {
//Delete offscreen bullets
//TODO: Fix this, one day.
for (std::vector<Bullet>::iterator i = shots.begin(); i != shots.end(); i++) {
if ( (shots.size() > 3) && (i->getY() < 0 || i->getY() > HEIGHT) )
i = shots.erase(i);
std::cout << "Erased!";
}
//Move bullets
for (long i = 0; i < shots.size(); i++) {
shots[i].move();
}
}
//Getter methods
Player Game::getPlayer(void) { return p; }
Invader* Game::getEnemies(void) { return *enemies; }
Invader* Game::getEnemy(int indexy, int indexx) { return enemies[indexy, indexx]; }
std::vector<Bullet> Game::getShots(void) {return shots;}
int Game::getEnemiesX(void) { return enemiesx; }
int Game::getEnemiesY(void) { return enemiesy; }
The difficulty in solving this is the fact that the program behaves differently each time it's run. Sometimes it will segfault on launch, sometimes after the mouse has been clicked twice or two minutes down the track and 20+ shots later.
Just wanted to try and get some more experience eyes on this code and see what really is happening.