Using Polygons to Detect Collision

You can use the Polygon class to help you detect hits in a shape that is not a rectangle or circle. You define points on a polygon to surround your shape. The x coordinates will be stored in an array of int and the corresponding y coordinates will be stored in another array of ints. In the example below the x's are stored in an array xs and the y's in array ys. In my example there are 9 points that define the polygon that surrounds the ship. To create the polygon object I did:

Polygon p = new Polygon(xs,ys,9);

To see if a point is inside the polygon I did:

if (p.contains(x, y))

contains is a boolean method that returns true if the point specified by the two parameters in inside or on the boundary of the polygon object. If will return false otherwise.

The class ImageIcon can be used to store images (such as .jpg, .gif and .png)

Link to ship image for this example

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class PolyImage 
{
   JFrame frame = new JFrame("Polygon and Image Example");
   ImageIcon ship;
   Drawing draw = new Drawing();
   boolean clickedInside = false;
   int[] xs = {25,200,220,250,380,390,385,50,25};
   int[] ys = {250,210,130,205,190,200,240,310,280};
   Polygon p = new Polygon(xs,ys,9);

   public PolyImage()
   {
      ship = new ImageIcon("ship.jpg");
      JPanel pane = (JPanel)frame.getContentPane();
      pane.add(draw, "Center");
      draw.addMouseListener(new MouseListen());
      frame.setSize(407, 425);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
   
   public static void main(String[] args)
   {
      new PolyImage();
   }
   
   class Drawing extends JComponent
   {
      public void paint(Graphics g)
      {
         g.drawImage(ship.getImage(),0,0, 400, 400,this);
         g.setColor(Color.red);
         if (clickedInside)
            g.fillPolygon(p);
      }     
   }
   
   class MouseListen extends MouseAdapter
   {
      public void mouseReleased(MouseEvent e)
      {
         int x = e.getX();
         int y = e.getY();
         if (p.contains(x, y))
            clickedInside = true;
         else
            clickedInside = false;
         draw.repaint();
      }
   }  
}