我应该如何让我的玩家长方形跳跃?

时间:2018-04-17 01:09:19

标签: java animation button javafx

当我按下跳转按钮时,我只是想让我的红色矩形跳起来。我似乎无法找到任何像动画甚至上升的东西,等待一段时间然后再回来。

import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.Button;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javafx.animation.PathTransition;
import javafx.scene.shape.*;
import javafx.util.Duration;

public class GUIPractice extends Application{

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

public void start (Stage primaryStage)
{
    Rectangle screen = new Rectangle(20, 20, 986, 500);
    Button JumpBtn = new Button("Jump");
        JumpBtn.setLayoutX(410);
        JumpBtn.setLayoutY(530);
        JumpBtn.setMinWidth(200);
        JumpBtn.setMinHeight(100);
    Rectangle player = new Rectangle(450, 420, 50, 100);
        player.setFill(Color.RED);

    Path path = new Path();

我相信下面是跳跃的地方,但我唯一能想到的是如何让矩形在屏幕上向上移动而不是向后移动。

    JumpBtn.setOnAction(new EventHandler<ActionEvent>()
    {
        public void handle(ActionEvent e) {
            player.setTranslateY(-40);
        }
    });

    Group root =  new Group(screen, JumpBtn, player);

    Scene scene = new Scene(root, 1024, 768);
    scene.setFill(Color.GREY);

    primaryStage.setTitle("GUIPractice");
    primaryStage.setScene(scene);
    primaryStage.show();
}

}

1 个答案:

答案 0 :(得分:0)

使用时间轴等动画移动Node,例如

double ty = player.getTranslateY();

// quadratic interpolation to simulate gravity
Interpolator interpolator = new Interpolator() {
    @Override
    protected double curve​(double t) {
        return t * (2 - t);
    }

};
Timeline timeline = new Timeline(new KeyFrame(Duration.ZERO,
                                              new KeyValue(player.translateYProperty(), ty, interpolator)),
                                 new KeyFrame(Duration.seconds(1),
                                              new KeyValue(player.translateYProperty(), ty-40, interpolator)));

// play forward once, then play backward once
timeline.setCycleCount(2);
timeline.setAutoReverse(true);

JumpBtn.setDisable(true);
timeline.setOnFinished(evt -> JumpBtn.setDisable(false));

timeline.play();