如何知道2张图像javafx之间的碰撞

时间:2016-01-28 22:49:00

标签: javafx collision-detection

如何在javaFx上获得2个图像或Bounds Intersect的碰撞?我移动了一张图片,但是如果我触摸第二张图片,我想要触发一些图像。

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();
        }
}

此代码无效

1 个答案:

答案 0 :(得分:0)

您可以为图像创建一个包装器,例如Sprite类,您可以使用该包装器为其提供x,y坐标。您可以在Rectangle2D形状的帮助下获得交集。

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());
    }
}