Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Lag when checking for collision in a top down shooter  (Read 2504 times)

0 Members and 1 Guest are viewing this topic.

URSvAir14

  • Newbie
  • *
  • Posts: 14
    • View Profile
Lag when checking for collision in a top down shooter
« on: March 01, 2014, 10:14:15 pm »
Hello all!

I'm currently programming the backbones for a top-down shooting game using SFML 2.1 and C++. I'm getting around to implementing projectiles and collision detection between projectiles and enemy units, however when I added the bounding box collision detection to my game loop it made the game drop from an even 60 FPS to a low 30 FPS.

My game-loop looks similar to this:
while(playing)
{
    //input
    //other processing
    if(BBCollision(player.getProjectile().getSprite(), enemy.getSprite()) == true){
        enemy.setDraw(false);
    }
    // output
}
And my function looks like this:
bool BBCollision(sf::Sprite sprite1, sf::Sprite sprite2){
        if(     sprite1.getPosition().x > sprite2.getPosition().x + sprite2.getGlobalBounds().width &&
                sprite1.getPosition().y > sprite2.getPosition().y + sprite2.getGlobalBounds().height &&
                sprite2.getPosition().x > sprite1.getPosition().x + sprite1.getGlobalBounds().width &&
                sprite2.getPosition().y > sprite1.getPosition().y + sprite1.getGlobalBounds().height)
                return true;
        else
                return false;
}

So can anyone point me what I did wrong and what I could do to get rid of the lag? Thank you in advance :)

AlejandroCoria

  • Jr. Member
  • **
  • Posts: 68
    • View Profile
    • alejandrocoria.games
    • Email
Re: Lag when checking for collision in a top down shooter
« Reply #1 on: March 01, 2014, 10:56:03 pm »
You would have to pass Sprites by reference instead of copying.

URSvAir14

  • Newbie
  • *
  • Posts: 14
    • View Profile
Re: Lag when checking for collision in a top down shooter
« Reply #2 on: March 01, 2014, 11:19:09 pm »
Ahh okay, thanks :D

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Re: Lag when checking for collision in a top down shooter
« Reply #3 on: March 02, 2014, 11:35:03 am »
And you can simplify the code:
// instead of
if (xy == true)

// write
if (xy)

// instead of
if (xy)
    return true;
else
    return false;

// write
return xy;

Furthermore, keep in mind that sf::Sprite has a getGlobalBounds() method.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development: