【问题标题】:How should I proceed in making my player rectangle jump?我应该如何让我的播放器矩形跳跃?
【发布时间】:2023-03-23 04:55:02
【问题描述】:

我只是想让我的红色矩形在你按下跳转按钮时跳起来。我似乎真的找不到像动画这样的东西,甚至找不到上升,等待一段时间然后再下降。

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

}

【问题讨论】:

    标签: java animation button javafx


    【解决方案1】:

    使用时间轴等动画来移动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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多