diff --git a/java/2-9-HitTest/TransformHittest.java b/java/2-9-HitTest/TransformHittest.java index a433079f1301496d2e3eff8b10e01d88de2d0f18..73d022b1da564643154f6641020a4d422cc7bd03 100644 --- a/java/2-9-HitTest/TransformHittest.java +++ b/java/2-9-HitTest/TransformHittest.java @@ -31,8 +31,8 @@ class Canvas extends JComponent { Point M = new Point(); // mouse point - AffineTransform AT1; - AffineTransform AT2; + AffineTransform AT1; // transform matrix for shape1 + AffineTransform AT2; // transform matrix for shape2 // the house shape (model position is centred at top left corner) @@ -47,13 +47,12 @@ class Canvas extends JComponent { Canvas() { - // create transformation matrices + // create transformation matrix for shape1 AT1 = new AffineTransform(); AT1.translate(350, 100); AT1.rotate(Math.toRadians(30)); - AT1.scale(1, 1); - // create another transformation matrices + // create another transformation matrix for shape2 AT2 = new AffineTransform(); AT2.translate(200, 300); AT2.rotate(Math.toRadians(30)); @@ -84,47 +83,50 @@ class Canvas extends JComponent { g2.drawPolygon(shape.xpoints, shape.ypoints, shape.npoints); - // Transformed Shape 1 + // Shape1 g2.setTransform(AT1); // Use Transform Matrix AT1 for shape1 g2.setColor(Color.RED); g2.drawPolygon(shape.xpoints, shape.ypoints, shape.npoints); - // hit test + + // hit testing Point MT = new Point(); try{ + // create an inverse matrix of AT1 AffineTransform IAT1 = AT1.createInverse(); + // apply the inverse transformation to the mouse position IAT1.transform(M, MT); + // check if original shape contains transformed mouse position if (shape.contains(MT.x, MT.y)) g2.setColor(Color.RED); else g2.setColor(Color.WHITE); - + g2.fillPolygon(shape); } catch (NoninvertibleTransformException e){ // error } - g2.fillPolygon(shape); - - // Transformed Shape 1 + // Shape2 g2.setTransform(AT2); // Use Transform Matrix AT2 for shape2 g2.setColor(Color.BLUE); g2.drawPolygon(shape.xpoints, shape.ypoints, shape.npoints); // hit test try{ + // create an inverse matrix of AT2 AffineTransform IAT2 = AT2.createInverse(); + // apply the inverse transformation to the mouse position IAT2.transform(M, MT); + // check if original shape contains transformed mouse position if (shape.contains(MT.x, MT.y)) g2.setColor(Color.BLUE); else g2.setColor(Color.WHITE); + g2.fillPolygon(shape); } catch (NoninvertibleTransformException e){ // error } - g2.fillPolygon(shape); // reset to transform g2.setTransform(ATG); } - - }