java - 我应该如何让我的玩家矩形跳跃?

标签 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();
}

}

最佳答案

使用时间轴等动画来移动节点,例如

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();

关于java - 我应该如何让我的玩家矩形跳跃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49868341/

相关文章:

Python - Pygame - 处理动画的角度和速度

Java:求解符号代数方程

java - 根据键值对HashMap的ArrayList进行排序

C++动画光标

具有圆形或弧段的 CSS 剪辑/路径/蒙版/形状动画

android - 在 Android java 中,如何长按蓝牙设备调用按钮?

Javascript - 如何访问按钮 onClick 中文本字段的值?

java - Spring中依赖资源发生变化时重新加载类

java - 在Java中使用instanceof运算符

ios - 如何隐藏 Xcode 6 中的按钮?