Translate transition not working right on keypress

Viewed 94

I'm trying to make a ball bounce up and down with the use of translate transition. I'm first trying to make the ball move up before it starts moving down. the code I used for moving it up is like this

public void moveUp(Circle player){
    TranslateTransition goUp = new TranslateTransition(Duration.millis(500),player);
    goUp.setByY(-20);
    goUp.play();
}

and I'm updating the value of the ball(player) on every keypress as follows(p.s player is of type Circle)

    scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent keyEvent) {
        if(keyEvent.getCode() == KeyCode.SPACE){
            moveUp(player);
            player.setCenterY(player.getCenterY-20);
        }
    }
});

the only problem is that the amount the ball moves is not the same as the amount I'm updating. Taking a few values as example(Take note that the player's original center was 400,300) I got 280 as the updated value of the player's centerY, yet the centreY of the ball on screen was at around the 260 which is far off. How do I fix this so that the player's centreY gets shifted by the same amount it moves on screen?

1 Answers

This is because the Circle (player) has a translateY property in addition to its centerY property as mentioned by @James_D. translateY is a property common to all nodes. Whenever a TranslateTransition is applied, the coordinates of the Node (player in this case) do not change. Instead its 'local origin' changes.

Circle player = new Circle(10);
TranslateTransition goUp = new TranslateTransition(Duration.millis(500),player);
goUp.setByY(-20);
goUp.play();

When this code is executed the origin for the player moves up by 20 pixels, and the centerY property stays the same. If the coordinates were originally (400,300), they stay the same, but are now referenced with respect to the new local origin.
This procedure of modifying the coordinate axes themselves, is common for all transformations as explained in the javadoc for Node.

A translation transformation is one which shifts the origin of the node's coordinate space along either the x or y axis.

Note that as with all transformations, the x, y, width, and height variables of the rectangle (which remain relative to the local coordinate space) have not changed, but rather the transformation alters the entire coordinate space of the rectangle.

If you want to change the centerY property instead of the translateY property, you can use the Timeline class instead of TranslateTransition. You could refer this SO answer for using the Timeline class for this purpose.

Related