I'm currently making space invaders (in OpenGL/SDL) and I'm running into an issue with the movement of the aliens. I have a 2-d vector of aliens (5 rows of 11) and I'm translating each in the x direction by a constant factor times elapsed time. If the right or leftmost alien in the vector hits either side of the screen, I decrement the y position of every alien. For some reason, when it collides the side of the screen, it infinitely translates downward in the y direction.
I thought that this would not happen since I wasn't multiplying the y position by elapsed time, but I think that its probably happening due to the fact that the update()
method is being called once per frame. Here is the code for the update function (inside of the enemies class which holds the 2-d array):
void update(float elapsed) {
//Update positions
float minX = -5.2;
float maxX = 5.2;
bool hitRight = false;
bool hitLeft = false;
//if the enemies haven't hit the right side
if (((enemyVect[0][rightmost]->x) + ((enemyVect[0][rightmost]->width) / 2.0) <= maxX)) {
for (int i = 0; i < enemyVect.size(); i++) {
for (int j = 0; j < enemyVect[i].size(); j++) {
enemyVect[i][j]->x += elapsed * 0.4 * xDirect;
}
}
}
//if they've hit the right side
else if(((enemyVect[0][rightmost]->x) + ((enemyVect[0][rightmost]->width) / 2.0) >= maxX)){
xDirect = -1;
hitRight = true;
for (int i = 0; i < enemyVect.size(); i++) {
for (int j = 0; j < enemyVect[i].size(); j++) {
if(hitRight)enemyVect[i][j]->y -= 0.6; //move each row of enemyVect down to the next level
}
}
hitRight = false;
}
//if the enemies haven't hit the left side
if (((enemyVect[0][leftmost]->x) -((enemyVect[0][leftmost]->width) / 2.0) >= minX)) {
for (int i = 0; i < enemyVect.size(); i++) {
for (int j = 0; j < enemyVect[i].size(); j++) {
enemyVect[i][j]->x += elapsed * 0.4 * xDirect;
}
}
}
//if they've hit the left side
else if (((enemyVect[0][leftmost]->x) - (enemyVect[0][leftmost]->width / 2.0) <= minX)) {
xDirect = 1;
for (int i = 0; i < enemyVect.size(); i++) {
for (int j = 0; j < enemyVect[i].size(); j++) {
enemyVect[i][j]->y -= 0.6; //move each row of enemyVect down to the next level
}
}
}
}
};
How should I go about making it so that the y position of each alien only gets decremented once right after the collision with either side of the screen?