Skip to content

Instantly share code, notes, and snippets.

@nhooyr
Created January 21, 2018 10:23

Revisions

  1. nhooyr created this gist Jan 21, 2018.
    57 changes: 57 additions & 0 deletions CollisionDetection.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    import javafx.application.Application;
    import javafx.geometry.Bounds;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.Pane;
    import javafx.scene.paint.Paint;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;

    public class CollisionDetection extends Application {

    @Override
    public void start(Stage primaryStage) {
    Label label = new Label();
    Pane paneA = new Pane();
    Pane paneB = new Pane();

    Rectangle objectA = new Rectangle(50, 30);
    objectA.setFill(Paint.valueOf("red"));
    objectA.setX(100);
    objectA.setY(100);
    objectA.setRotate(10);
    objectA.setSmooth(true);

    Rectangle objectB = new Rectangle(80, 40);
    objectB.setFill(Paint.valueOf("blue"));
    objectB.setRotate(-10);
    objectB.setX(115);
    objectB.setY(50);

    paneB.getChildren().add(objectB);
    paneA.getChildren().addAll(objectA, paneB);

    Bounds objA = objectA.localToScene(objectA.getBoundsInLocal());
    Bounds objB = objectB.localToScene(objectB.getBoundsInLocal());

    if (objA.intersects(objB)) {
    label.setText("ObjectA intersects ObjectB");
    } else {
    label.setText("ObjectA does not intersect ObjectB");
    }

    BorderPane root = new BorderPane(paneA);
    root.setBottom(label);
    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Collision Detection");
    primaryStage.setScene(scene);
    primaryStage.show();
    }

    public static void main(String[] args) {
    launch(args);
    }

    }