Constantly checking if a bullet has touched a node

You can check if the bullet intersects other using Shape.intersect() in a custom Interpolator supplied to each relevant KeyValue. The fragment below adds an Interpolator to shoot(), but you’ll need an identical one for each direction. The implementation is linear, simply returning t unchanged, but you might also look at this parabolic interpolator. I also made other a class variable, accessible to shoot(). I put a dozen bullets into the air with no perceptible delay. Note that you don’t need a start value: “one will be synthesized using the target values that are current at the time” the animation is played.

private Circle other = new Circle(100, 100, 10);
…
else {
    KeyValue end = new KeyValue(bullet.translateYProperty(), -800, new Interpolator() {
        @Override
        protected double curve(double t) {
            if (!Shape.intersect(bullet, other).getBoundsInLocal().isEmpty()) {
                System.out.println("Intersection");
            }
            return t;
        }
    });
    KeyFrame endF = new KeyFrame(Duration.seconds(10), end);
    timeline.getKeyFrames().addAll(endF);
}

Leave a Comment