Search code examples
sdlcollisiondetectionbullet

SDL 2 bullet collision not working?


I'm new to SDL 2 and I've been stuck on a collision detection between a bullet and a spaceship for some time.

I understand what has to happen, but I'm getting confused with what collides with what, and which way around to put the code. The collision detection doesn't work, and some other attempts I've made results in the bullet disappearing at the spaceships y coordinate, even if it is on the opposite side of the screen! I've based it around a lazy foo tutorial.

My whole code is here: http://codepad.org/YaCavBvm

My collision detection based around LazyFoo:

//sides of sprite rectangles
int leftBullet, leftEnemy;
int rightBullet, rightEnemy;
int topBullet, topEnemy;
int bottomBullet, bottomEnemy;

//Calculate the sides of bullet
leftBullet = posBullet.x;
rightBullet = posBullet.x + BULLET_WIDTH;
topBullet = posBullet.y;
bottomBullet = posBullet.y + BULLET_HEIGHT;

//Calculate the sides of enemy
leftEnemy = posEnemy.x;
rightEnemy = posEnemy.x + SPRITE_WIDTH;
topEnemy = posEnemy.y;
bottomEnemy = posEnemy.y + SPRITE_HEIGHT;

for (int i=0; i<MAX_BULLETS; i++)
{
    if (topBullet == bottomEnemy)
    {
        arrayofBullets[i].isActive = false;
    }
}

Solution

  • In theory, a bullet grazing the bottom of your foot is a hit but you could regard that as a hit or a miss. Try the following

    if (topBullet >= topEnemy &&
        bottomBullet <= bottomEnemy &&
        leftBullet >= leftEnemy &&
        rightBullet <= rightEnemy)
        // What happens when the bullet hits
    

    This will take care of the partial hits. The one in lazyfoo is for one particular case which is correct in the context of the example.