I'm making space invaders (in OpenGL/SDL) and I'm currently having issues with getting the collisions (box collisions) between the bullets and the enemies to be properly detected. In my update()
function, I have a nested for loop which iterates through all of entities (for each bullet) detecting if each bullet has collided with it. To do this, I have a function checkCollision()
in which I'm calculating the dimensions of each enemy and bullet that gets passed in and then checking if the "boxes" for each entity are intersecting:
Function for checking collisions
bool checkCollision(Enemy* anEnemy, Bullet* aBullet) {
float enemyTop = anEnemy->y + (anEnemy->height / 2.0f);
float enemyBottom = anEnemy->y - (anEnemy->height / 2.0f);
float enemyRight = anEnemy->x + (anEnemy->width / 2.0f);
float enemyLeft = anEnemy->x - (anEnemy->width / 2.0f);
float bulletTop = aBullet->y + (aBullet->height / 2.0f);
float bulletBottom = aBullet->y - (aBullet->height / 2.0f);
float bulletLeft = aBullet->x - (aBullet->width / 2.0f);
float bulletRight = aBullet->x + (aBullet->width / 2.0f);
//This is supposed to check that if the objects are not intersecting, return false
if (
(bulletBottom > enemyTop) ||
(bulletTop < enemyBottom) ||
(bulletLeft > enemyRight) ||
(bulletRight < enemyLeft)
) {
return false;
}
else {
return true;
}
}
Code to check collisions for each enemy in update function
//Check if each of the bullets has hit any of the enemies
for (int i = 0; i < bullets.size(); i++) {
for (int j = 0; j < entities.size(); j++) {
if (entities[j] != nullptr && bullets[i] != nullptr) {
if (checkCollision(entities[j], bullets[i])) {
std::cout << "bullets y position: " << bullets[i]->y << std::endl;
std::cout << " hit enemy y position: " << entities[j]->y << std::endl;
std::cout << "bullets x position: " << bullets[i]->x << std::endl;
std::cout << " hit enemy x position: " << entities[j]->x << std::endl;
delete entities[j];
entities[j] = nullptr;
delete bullets[i];
bullets[i] = nullptr;
}
}
}
}
For some reason, when the bullet it shot from the spaceship (player), the collisions are detected before the bullet even reaches the enemy on the screen and I get the following console output:
bullet y position: 0.610021
enemy y position: 1.85
bullet x position: 0
enemy x position: -1.0335
How should I be structuring the collision detection differently so that the objects are actually intersecting before the collision is detected?
Edit:
I was able to modify the code to make the collisions happen closer to the enemies but they still aren't very precise. I had been scaling the entities by the widths and heights so I decided to reduce the scaling factor. The problem now is that the bullets are taking out two enemies before they are destroyed.
Full Code for reference
The image below shows the instance in which the collision is being detected between the bullet and the enemy