1
\$\begingroup\$

I am developing a game using Libgdx and Ashley, and I would like to know the best way to detect collisions between different entities. Currently I have been using a ContactListener that detects contacts between different types of entities but I think this could negatively affect the performance of the game, especially considering that in a mobile application.

I would like to clarify that the type of contact I am wanting to perform is between the player and coins or entities in which it is not necessary to have a body.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

I assume both the player and the coins are circles for easy collision detection. So you can use the method shown in this blog https://www.gamedevelopment.blog/collision-detection-circles-rectangles-and-polygons/ which is:

public boolean isCirclesColliding(Circle cir1, Circle cir2){
    float sidea = Math.abs(cir1.x - cir2.x);
    float sideb = Math.abs(cir1.y - cir2.y);
    sidea = sidea * sidea;
    sideb = sideb * sideb;
    float distance = (float) Math.sqrt(sidea+sideb);
    if(circle1.radius + circle2.radius < distance){
        return true;
    }
   return false;
}

Now, to limit the amount of checks you are doing against player you can reject all coins that are too far from the player since any coin over player.radius + coin.radius cannot be touching.

if(coin.radius + player.radius < math.abs(player.x - coin.x)){
    // only coins close enough on x axis enter here
    if(coin.radius + player.radius < math.abs(player.y + coin.y)){
         //only coins close enough on both x axis and y axis enter here
         if(isCirclesColliding(player,coin)){
             // contact is happeneing
         }
    }
} 

This can be put in your system that loops for all coins

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .