Search code examples
javafxcollision-detection

How to know collision between 2 images javafx


how to get the collision of 2 images or Bounds Intersect on javaFx? I move one image but if I touch the second image I want to trigger something.

gc.drawImage( img2, 0, 400, 950, 100 );
    gc.drawImage( img3, 200, 200, 150, 50 );

if (event.getCode() == KeyCode.RIGHT ){
            if(img2.intersects(img3.getBoundsInLocal())){
            doSomething();
        }
}

this code doesn't work


Solution

  • You can create a wrapper for the image, a Sprite class for example, and you can use that wrapper to give it x,y coordinates. You can get the intersection with the help of a Rectangle2D shape.

    import javafx.geometry.Rectangle2D;
    import javafx.scene.canvas.GraphicsContext;
    import javafx.scene.image.Image;
    
    public class Sprite {
    
        private Image image;
        private double positionX;
        private double positionY;
        private double width;
        private double height;
    
        public Sprite(Image image) {
            this.image = image;
            width = image.getWidth();
            height = image.getHeight();
            positionX = 0;
            positionY = 0;
        }
    
        public void setPosition(double x, double y) {
            positionX = x;
            positionY = y;
        }
    
        public void render(GraphicsContext gc) {
            gc.drawImage(image, positionX, positionY);
        }
    
        public Rectangle2D getBoundary() {
            return new Rectangle2D(positionX, positionY, width, height);
        }
    
        public boolean intersects(Sprite spr) {
            return spr.getBoundary().intersects(this.getBoundary());
        }
    }