Constantly checking if a bullet has touched a node

前端 未结 3 1289
太阳男子
太阳男子 2020-11-30 13:13

I have a very simple program where you can use your W, A, S, D and space keys to shoot. All of the shooting and movin

相关标签:
3条回答
  • 2020-11-30 13:51

    In general, when you must "constantly observe" something in an OO language, the best solution is to use the Observer pattern.

    0 讨论(0)
  • 2020-11-30 13:52

    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);
    }
    
    0 讨论(0)
  • 2020-11-30 13:59

    What you need is something that will check for collision every time you draw a frame in your game. A timer would run in a separate thread which could work, but would be much harder to synchronize with the game.

    0 讨论(0)
提交回复
热议问题