Objects becoming null in C++ vector<Object*> - c++

I'm working on a game in C++, and have a player object and a bullet object. I have a std::vector collection for both kinds of object, defined earlier in my code like so:
std::vector<Player*> players;
std::vector<Bullet*> bullets;
My problem happens in my main game loop, where I do all of my update logic. Using a for loop to check each player and update him, I get any bullets he has spawned and add them to the bullets vector.
// update players
for (int i = 0; i < players.size(); ++i){
Player *player = players[i];
player->Update(delta);
// get bullets
for (int b = 0; b < player->Bullets.size(); ++b){
// THIS IS WHERE THINGS GET WEIRD FOR PLAYER 2
Bullet *bull = player->Bullets[i];
bullets.push_back(bull);
}
player->Bullets.clear();
}
While my first player works fine - he can shoot as much as he wants - when you get to the second player, making him shoot causes an EXC_BAD_ACCESS later on when I iterate through the bullets vector. As I was stepping through with a debugger (using Xcode), when I get to the part below my comment ("// THIS IS WHERE THINGS GET WEIRD FOR PLAYER 2"), I notice that the bullet is NULL and the player is NULL as well. Somewhere between calling that player's update method and where I pull the bullets out, things go horribly wrong.
I've been debugging this for several hours now, and I'm wondering what I am missing.
Thanks!

It's a simple typo:
Bullet *bull = player->Bullets[b];
^ not i
You could avoid this kind of mistake using range-based loops (C++11 or later):
for (Player * player : players) {
player->Update(delta);
for (Bullet * bullet : player->Bullets) {
bullets.push_back(bullet);
}
player->Bullets.clear();
}
and/or replacing the inner loop with
bullets.insert(bullets.end(), player->Bullets.begin(), player->Bullets.end());

Related

Nested loops, deleting from vectors

I am trying to make my simple game and I came across small issue. So I have 2 vectors of pointers.
One is for bullets and one is for enemy units.
First I tried to iterate through all of my bullets and then in second loop iterate through my enemies and when I find collision I erase enemy unit and bullet, but erasing bullets is crashing my game, so I figured out that I shouldnt erase from vector while its still iterating in first loop.
My second ide was something like this:
std::vector<Bullet*>::iterator remove = std::remove_if(bullets.begin(), bullets.end(),
[&](Bullet* x)
{
for (std::vector<EnemyUnit*>::iterator it = enemyUnits.begin(); it != enemyUnits.end(); ++it)
{
if (x->collision->CheckCollision((*it)->collision))
{
enemyUnits.erase(it);
return true;
}
else
{
return false;
}
}
});
bullets.erase(remove, bullets.end());
So it seems to work in a way, but my bullets can only collide with one enemy at a time and it seems like its not checking for all enemies. For example I shoot 5 bullets and firstly they can only collide with one enemy and after one bullet kills enemy other bullets will be able to collide with second enemy and so on . It seems like
for (std::vector<EnemyUnit*>::iterator it = enemyUnits.begin(); it != enemyUnits.end(); ++it)
Doesnt take place and it only gets one enemy? Is it wrong way to do it?
I need to use pointers and vectors, because its for my project.
The predicate for std::remove_if returns after the first check, no matter what.
To fix this, the predicate can return on a collision, or at the end (after the loop) on no collision, e.g.
for (auto it = enemyUnits.begin(); it != enemyUnits.end(); ++it)
{
if (x->collision->CheckCollision((*it)->collision))
{
enemyUnits.erase(it);
return true;
}
}
return false;
This way, if a collision is detected, it will exit early and return true.
If there's no collision with any enemy, it will stop after the loop and return false.
Answer advising to remove the return statements is correct. The return statements are exiting the inside loop early, but that isn't the only problem. Removing those returns will reveal the next problem. You need:
it = enemyUnits.erase(it);
to correctly set the iterator after an erase to prepare for the next pass through the loop.

Snake Game - Can't get snake body to follow snake head

I have been working on a snake game using sfml and c++ but I am having trouble getting the tail of my snake to follow the snake head which is defined as Snake[0] in my code below. I have implemented code that I think should work but doesn't which is the following
for (int i = 1; i < snakeSize; i++)
{
snakePartX[i] = snakePartX[i-1];
snakePartY[i] = snakePartY[i-1];
}
The way I understand it (and I am probably incredibly wrong and would appreciate if anyone could point out what is actually happening here) is that, that piece of code should set the value of a snake body part to the position of where the previous body part WAS located so that when the program loops they are set to follow the snake as it travels.
What actually does happen though is that when the snake eats an apple the snake will gain 1 block to its tail, but will not grow any farther.
In the classic snake game, the snake is made up of segments. Each segment contains the coordinate of the segment (among other attributes).
Specifically, the snake is a container of segments. The container is your choice, but I recommend a queue.
With the queue, a new head segment is added into the queue and a tail segment removed.
Here's a code fragment to help:
class Snake_Segment
{
public:
int column;
int row;
};
typedef std::deque<Snake_Segment> Segment_Container;
int main(void)
{
Segment_Container snake_body;
Snake_Segment head;
head.row(25);
head.column(30);
snake_body.push_back(head);
Snake_Segment tail = head;
++tail.column;
snake_body.push_back(tail);
return EXIT_SUCCESS;
}
Why do index zero here? Doesn't it get done as part of the for loop too?
Snake[0].setPosition(snakePartX[0], snakePartY[0]);
for(int i = 0; i < snakeSize; i++)
{
Snake[i].setPosition(snakePartX[i], snakePartY[i]);
}
I'm concerned about this section :
snakeSize += 1;
}
Apple.setPosition(applePos.x, applePos.y);
window.draw(Apple);
for(int i = 0; i < snakeSize; i++)
{
window.draw(Snake[i]);
}
Make sure you don't exceed 20 as your parts are a simple array and you will run into problems once you get 20 parts. More importantly, you never set the value for Snake[i] for the new snakeSize. So when you get an apple, you'll use uninitialized memory to draw one snake part.
Another potential problem :
//Clock to set snake speed
ElapsedTime = clock.getElapsedTime();
if(ElapsedTime.asSeconds() >= snakeSpeed)
{
for(int i = 1; i < snakeSize; i++)
{
snakePartX[i] = snakePartX[i - 1];
snakePartY[i] = snakePartY[i - 1];
}
You allow keyboard input to move the snake head along, but you only move the body when the timer expires. So you head can slide way away from the body and the body doesn't move unless the timer goes off.
I printed the field of snake game as a Field[x][y]. So by below code the body of snake following the head. Also, optionMoveNumber==0 in other function checked if Field[x][y]==food or not which means did the snake eat the food of not.
int m=1;
void Snake::Movement(int x, int y){
movey[0]=firstTaily; //first place
movex[0]=firstTailx; //first place
movex[m]=x;
movey[m]=y;
for(int n=m; n>=m-ntail; n--){
Field[movey[n]][movex[n]]=Field[movey[n-1]][movex[n-1]];
}
if(optionMoveNumber==0){
Field[movey[m-1]][movex[m-1]]=tail;
}
else{
Field[movey[m-ntail-1]][movex[m-ntail-1]]=space;
}
m++;
}

Collision of two sprite lists - SFML 2.0

I am making a simple game in SFML 2 and it came smoothly so far. I created two sf::Sprite lists, one for enemies and one for lasers. The enemies spawn randomly off-screen and the lasers are created whenever input is given. I created a collision loop for both the lists and executed my code. There are no compile time and run time errors. The laser-enemy collision works fine for the first 3 to 4 enemies but after that, the collision does not occur. What might be causing this problem? Please help me on this. Thanks. Here's my code.
std::list<sf::Sprite>::iterator enemyit = enemy.begin(), next;
std::list<sf::Sprite>::iterator greenlaserit = greenlaser.begin(), reload;
while(enemyit != enemy.end())
{
next = enemyit;
next++;
while(greenlaserit != greenlaser.end())
{
reload = greenlaserit;
reload++;
if(enemyit->getGlobalBounds().intersects(greenlaserit->getGlobalBounds()))
{
enemy.erase(enemyit);
greenlaser.erase(greenlaserit);
++erased;
}
greenlaserit = reload;
}
enemyit = next;
}
It seems to be that you are doing a lot of iterator manipulation and that is likely to be where the problem is occurring.
If you can use c++11, I would suggest looking into the for each loop (http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html), to keep things really simple to read and understand (and thus, easier to debug).
You could do something like this:
std::list<sf::Sprite> enemies;
std::list<sf::Sprite> lasers;
for (sf::Sprite enemy: enemies) {
for (sf::Sprite laser : lasers) {
if (enemy.getGlobalBounds().intersects(laser.getGlobalBounds())) {
enemies.remove(enemy);
lasers.remove(laser);
}
}
}
Edit: otherwise, one method I have found for figuring out an iterator problem is stepping through it by hand. I draw two rectangles with cells for each location, and keep track of the iterators and run through the logic step by step. Before each iteration of your logic, write down your expected results. Then go through it by hand and see if your results match your expectations.

C++ do while loop

I have a vector holding 10 items (all of the same class for simplicity call it 'a'). What I want to do is to check that 'A' isn't either a) hiding the walls or b) hiding another 'A'. I have a collisions function that does this.
The idea is simply to have this looping class go though and move 'A' to the next position, if that potion is causing a collision then it needs to give itself a new random position on the screen. Because the screen is small, there is a good chance that the element will be put onto of another one (or on top of the wall etc). The logic of the code works well in my head - but debugging the code the object just gets stuck in the loop, and stay in the same position. 'A' is supposed to move about the screen, but it stays still!
When I comment out the Do while loop, and move the 'MoveObject()' Function up the code works perfectly the 'A's are moving about the screen. It is just when I try and add the extra functionality to it is when it doesn't work.
void Board::Loop(void){
//Display the postion of that Element.
for (unsigned int i = 0; i <= 10; ++i){
do {
if (checkCollisions(i)==true){
moveObject(i);
}
else{
objects[i]->ResetPostion();
}
}
while (checkCollisions(i) == false);
objects[i]->SetPosition(objects[i]->getXDir(),objects[i]->getYDir());
}
}
The class below is the collision detection. This I will expand later.
bool Board::checkCollisions(int index){
char boundry = map[objects[index]->getXDir()][objects[index]->getYDir()];
//There has been no collisions - therefore don't change anything
if(boundry == SYMBOL_EMPTY){
return false;
}
else{
return true;
}
}
Any help would be much appreciated. I will buy you a virtual beer :-)
Thanks
Edit:
ResetPostion -> this will give the element A a random position on the screen
moveObject -> this will look at the direction of the object and adjust the x and Y cord's appropriately.
I guess you need: do { ...
... } while (checkCollisions(i));
Also, if you have 10 elements, then i = 0; i < 10; i++
And btw. don't write if (something == true), simply if (something) or if (!something)
for (unsigned int i = 0; i <= 10; ++i){
is wrong because that's a loop for eleven items, use
for (unsigned int i = 0; i < 10; ++i){
instead.
You don't define what 'doesn't work' means, so that's all the help I can give for now.
There seems to be a lot of confusion here over basic language structure and logic flow. Writing a few very simple test apps that exercise different language features will probably help you a lot. (So will a step-thru debugger, if you have one)
do/while() is a fairly advanced feature that some people spend whole careers never using, see: do...while vs while
I recommend getting a solid foundation with while and if/else before even using for. Your first look at do should be when you've just finished a while or for loop and realize you could save a mountain of duplicate initialization code if you just changed the order of execution a bit. (Personally I don't even use do for that any more, I just use an iterator with while(true)/break since it lets me pre and post code all within a single loop)
I think this simplifies what you're trying to accomplish:
void Board::Loop(void) {
//Display the postion of that Element.
for (unsigned int i = 0; i < 10; ++i) {
while(IsGoingToCollide(i)) //check is first, do while doesn't make sense
objects[i]->ResetPosition();
moveObject(i); //same as ->SetPosition(XDir, YDir)?
//either explain difference or remove one or the other
}
}
This function name seems ambiguous to me:
bool Board::checkCollisions(int index) {
I'd recommend changing it to:
// returns true if moving to next position (based on inertia) will
// cause overlap with any other object's or structure's current location
bool Board::IsGoingToCollide(int index) {
In contrast checkCollisions() could also mean:
// returns true if there is no overlap between this object's
// current location and any other object's or structure's current location
bool Board::DidntCollide(int index) {
Final note: Double check that ->ResetPosition() puts things inside the boundaries.

Killing the invaders doesn't work in C++

I know that in order to kill invaders in C++, I need to make a collider.
However, nothing will ever kill the invaders in that game.
Here's the code in the header:
bool DoCollision(float Xbpos, float Ybpos, int BulWidth, int BulHeight, float Xipos, float Yipos, int InvWidth, int InvHeight);
This is the function I'm initializing:
bool Game::DoCollision(float Xbpos, float Ybpos, int BulWidth, int BulHeight, float Xipos, float Yipos, int InvWidth, int InvHeight) {
if (Xbpos+BulWidth < Xipos || Xbpos > Xipos+InvWidth) return false;
if (Ybpos+BulHeight < Yipos || Ybpos > Yipos+InvHeight) return false;
return true;
}
And this is what happens if somebody presses the space key:
if (code == 57) { //Space
myKeyInvader.MeBullet.Active = true;
myKeyInvader.MeBullet.Xpos = myKeyInvader.Xpos + 10;
myKeyInvader.MeBullet.Ypos = myKeyInvader.Ypos - 10;
myKeyInvader.MeBullet.yvuel = 0.2;
myKeyInvader.MeBullet.BulletP->CopyTo(m_Screen,myKeyInvader.Xpos,myKeyInvader.Ypos);
if (DoCollision(Invaders[counter].MyBullet.Xbpos,Invaders[counter].MyBullet.Ybpos,Invaders[counter].MyBullet.BulWidth,
Invaders[counter].MyBullet.BulHeight,Invaders[counter].Xipos,Invaders[counter].Yipos,Invaders[counter].InvWidth,Invaders[counter].InvHeight)) {
//myKeyInvader.Ypos = 100;
Invaders[counter].Active = false;
printf("Collide!\n");
}
}
Does anybody know what's going wrong?
The problem isn't C++. The problem is how you are using it. The only way you'll get a kill with your code as written is if the invader is right on top of you. But that's too late. The alien invader has already killed you.
What you need to do is make those bullets into objects that you propagate over time, just like your invaders are objects that you propagate over time. The response to the user pressing a space key should be to add a new instance of a bullet to the set of active bullets. Each of those active bullets has a position that changes with time. On each time step, you should advance the states of the active invaders per the rules that dictate how invaders move and advance the states of the active bullets per the rules that dictate how bullets move. Remove bullets when they reach the top of the screen, and if an alien invader reaches the bottom of the screen, game over.
After propagating, removing off-screen bullets, and checking for game over, you want to check for collisions between each of the N bullets with each of the M invaders. When a collision is detected, remove the bullet from the set of active bullets and delete the alien invader from the set of active invaders. And of course you'll want some nifty graphics to show the user that another alien bit the dust.
Aside: Being an NxM problem, this check might be the biggest drain on CPU usage. You can speed this up with some simple heuristics.
You could manage the collections of alien invaders and bullets yourself, carefully using new and delete so as to prevent your invaders and bullets from killing your program with a memory leak. You don't have to do this. C++ gives you some nifty tools to manage these collections. Use one of the C++ standard library collections instead of rolling your own collection. For example, std::vector<AlienInvader> invaders; or std::list<AlienInvader> invaders, and the same for bullets. You'll be deleting from the middle a lot, which suggests that std::list or std::deque might be more appropriate than std::vector here.
You test the collision for the fired item just when they are created
Shouldn't be the test collision done in the main loop for each existing item at each frame ?
Don't worry, C++ has got all you need to kill invaders :)))
It's not easy to give advice based on so little code, but here the only logical error seems to be you test for collision only when space is pressed; you should test for it in an outside loop probably:
if (code == 57) { //Space
myKeyInvader.MeBullet.Active = true;
myKeyInvader.MeBullet.Xpos = myKeyInvader.Xpos + 10;
myKeyInvader.MeBullet.Ypos = myKeyInvader.Ypos - 10;
myKeyInvader.MeBullet.yvuel = 0.2;
myKeyInvader.MeBullet.BulletP->CopyTo(m_Screen,myKeyInvader.Xpos,myKeyInvader.Ypos);
}
From a logical point of view, pressing Space should fire a bullet: the starting position for the bullet is set, and so is its speed on the Y axis (so that it goes up).
The code that check for collision should go outside of this if block. In fact, this block of code is executed only if you're still pressing space -that is: still firing-. Should collision be checked only if you're "still firing"? Do the fact that you fired a bullet and started waiting for it to destroy the invader interfere in some way with the fact that this bullet can reach the invader and, indeed, destroy it? Of course not!
if (DoCollision(Invaders[counter].MyBullet.Xbpos,Invaders[counter].MyBullet.Ybpos,Invaders[counter].MyBullet.BulWidth,
Invaders[counter].MyBullet.BulHeight,Invaders[counter].Xipos,Invaders[counter].Yipos,Invaders[counter].InvWidth,Invaders[counter].InvHeight)) {
//myKeyInvader.Ypos = 100;
Invaders[counter].Active = false;
printf("Collide!\n");
}
You want collision to be checked in an outside loop, the same that probably also contains the checks for key presses. In this way, even if you're just looking at the screen and waiting, the program keeps testing the condition and, when it's fulfilled, code associated with the event of collision is executed (that is: an invader is "inactivated").
You say //Space , is that what it is or should it be 32 (if ASCII) instead of 57? Does the program flow into the if==57 block?
Your code looks fine, but you need two loops around the collision checker: one for checking all invaders (not just one of them) and another one to check at every bullet position along its trajectory, not just the moment when it leaves the gun.
I will assume we have an auxiliary function that moves the bullet and returns whether it is still inside the screen:
bool BulletIsInScreen();
Then we can write the loops:
if (code == 57) { // Space
while (BulletIsInScreen()) {
for (size_t i = 0; i < counter; ++i) { // counter is the number of invaders,
// according to your comment to your own answer
myKeyInvader.MeBullet.Active = true;
myKeyInvader.MeBullet.Xpos = myKeyInvader.Xpos + 10;
myKeyInvader.MeBullet.Ypos = myKeyInvader.Ypos - 10;
myKeyInvader.MeBullet.yvuel = 0.2;
myKeyInvader.MeBullet.BulletP->CopyTo(m_Screen,myKeyInvader.Xpos,myKeyInvader.Ypos);
if (DoCollision(Invaders[i].MyBullet.Xbpos, Invaders[i].MyBullet.Ybpos,
Invaders[i].MyBullet.BulWidth, Invaders[i].MyBullet.BulHeight,
Invaders[i].Xipos, Invaders[i].Yipos,
Invaders[i].InvWidth, Invaders[i].InvHeight)) {
//myKeyInvader.Ypos = 100;
Invaders[i].Active = false;
printf("Collide!\n");
}
}
}
}
Now this should work as expected.