Zach Zach - 1 year ago 118
Java Question

JavaFX - Why is the score not incrementing?

the game

I just added the animation part and now whenever I click on the duck it does nothing to the score, but when I comment out the animation code and the duck stays still, it increments just fine.

Full Code


KeyValue start = new KeyValue(duck.translateXProperty(), 10);
KeyValue end = new KeyValue(duck.translateXProperty(), 400);
KeyFrame startF = new KeyFrame(Duration.ZERO, start);
KeyFrame endF = new KeyFrame(Duration.seconds(10), end);
Timeline tl = new Timeline(startF, endF);

Event Handler for Clicks:

scene.setOnMouseClicked(event -> {
if (duck.contains(event.getX(), event.getY())){
//increment score

Answer Source

Based on what you've said in the question and comments:

when I comment out the animation code and the duck stays still, it increments just fine

Whenever I click the ducks initial position, it increments the score

I'm guessing that your ImageView (the duck)'s bounding box is not getting updated.

From the ImageView docs:

This variable can be used to alter the location of a node without disturbing its layoutBounds, which makes it useful for animating a node's location.

This means that the image itself moves, and the duck is still considered to be at its initial position, so the contains() method wouldn't work. You'll have to find a different way of figuring out clicks

Perhaps what you could do is use the getTranslateX() property for your contains(), it seems like it'll get the current offset of the visual duck from the geometry duck:

scene.setOnMouseClicked(event -> {
    double rawMouseX = event.getX();
    double rawMouseY = event.getY();

    double normalizedMouseX = rawMouseX - duck.getTranslateX();
    double normalizedMouseY = rawMouseY - duck.getTranslateY();

    if (duck.contains(normalizedMouseX, normalizedMouseY)){
        //increment score

Disclaimer: I have no experience with JavaFX, I'm going mainly off of vanilla Java experience

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download