Sign in to follow this  

Sfml Collision Efficiency Issue

Recommended Posts

Hi I'm Moritz and currently I'm working on an Entity-on-Entity  2D-Collision-Checking in SFML. The Collision detection and resolving works pretty fine but my FPS are very bad(70-90 FPS with 5 entities being checked).

Please Help me to make my code more efficient:

 

 

 

void EntityManager::EntityCollsionCheck()
{
    for (int i = 0; i < m_entities.size(); i++) {
        for (int j = 1; j < m_entities.size(); j++)
        {

            sf::Vector2f pos_i = m_entities.find(i)->second->GetPosition();
            sf::Vector2f pos_j = m_entities.find(j)->second->GetPosition();

            int dx = 0, dy = 0;
            while (dx*dx + dy*dy<5 * 42*42)
            {
                pos_i.x += dx / 200.0;
                pos_i.y += dy / 200.0;
                pos_j.x -= dx / 200.0;
                pos_j.y -= dy / 200.0;

                dx = pos_i.x - pos_j.x;
                dy = pos_i.y - pos_j.y;
                
                

                m_entities.find(i)->second->SetPosition(pos_i);
                m_entities.find(j)->second->SetPosition(pos_j);


                if (!dx && !dy) break;
            }


        }

    }



}

Share this post


Link to post
Share on other sites
It sounds like you are using a CRT monitor and have VSync enabled.

This change will have a big impact with a large number of compares, not so much for so few though...
int j = 1
in
for (int j = 1; j < m_entities.size(); j++)
to
int j = i + 1

Share this post


Link to post
Share on other sites

It sounds like you are using a CRT monitor and have VSync enabled.

This change will have a big impact with a large number of compares, not so much for so few though...

int j = 1
in
for (int j = 1; j < m_entities.size(); j++)
to
int j = i + 1

this will give better performance.....but want *even better*?  you need to somehow group your entities spatially and only check against those that are near to one another.  Quadtree (2D) or octree (3D) are pretty good candidates for this.  If you have a tilemap then can also store references in your tile (eats of memory though).  Then you can spatially tell which entities are near one another and only check those.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this