0

I'm creating a game called "Asteroids" and all the objects that I'm drawing are with polygons. I have a few methods to check the collision between two polygons, but it doesn't work all the time. For example, it might be working bad when I check collision when the player of the game is currently moving around the screen.

Here is the code of the class that contains all the methods for game objects collisions. Thanks for the helpers.

public class Hits
{
   private static boolean isPolygonCollidingWithAnotherPolygon(Polygon p1, Polygon p2) {
      for (int i = 0; i < p1.npoints; i++) {
         Point p = new Point(p1.xpoints[i], p1.ypoints[i]);
         if (p2.contains(p))
            return true;
      }

      for (int i = 0; i < p2.npoints; i++) {
         Point p = new Point(p2.xpoints[i], p2.ypoints[i]);
         if (p1.contains(p))
            return true;
      }

      return false;
   }
   
   // ball with spaceship
   public static boolean isBallHittingSpaceship(Ball b,Spaceship s)
   {
      return b.isFromShooter && s.getPolygon().contains(b.getX(),b.getY());
   }
   
   // ball with asteroid
   public static boolean isBallHittingAsteroid(Ball b,Asteroid a)
   {
      return a.getPolygon().contains(b.getX(),b.getY());
   }

   // ball with player
   public static boolean isShooterHittingBall(Ball b, Player player)
   {
      return !b.isFromShooter && player.getPolygon().contains(b.getX(), b.getY());
   }
   
   // spaceship with asteroid
   public static boolean isSpaceshipHittingAsteroid(Spaceship spaceship ,Asteroid asteroid)
   {
            return isPolygonCollidingWithAnotherPolygon(spaceship.getPolygon(),  asteroid.getPolygon());
   }
   
   // asteroid with player
   public static boolean isShooterHittingAsteroid(Player player , Asteroid asteroid)
   {
        return isPolygonCollidingWithAnotherPolygon(player.getPolygon(), asteroid.getPolygon());
   }

   // spaceship with player
   public static boolean isSpaceshipHittingShooter(Spaceship spaceship, Player player)
   {
        return isPolygonCollidingWithAnotherPolygon(spaceship.getPolygon(), player.getPolygon());
   }
}

As seen in the code, I tried to check every possible point in one polygon, if it's in the other polygon, but still it doesn't work properly.

  • the polygons do not need to share a point to overlap or touch, this might help https://stackoverflow.com/questions/753140/how-do-i-determine-if-two-convex-polygons-intersect – Pavel Jan 12 '23 at 14:27
  • Explain the multithreading? – user253751 Jan 13 '23 at 08:25

0 Answers0