如何在JavaFX中使球从墙壁d起?

如何在JavaFX中使球从墙壁d起?,第1张

如何在JavaFX中使球从墙壁d起

一个提示:您应该避免比较双精度值的完全相等

a == b

只需对代码进行一些小的更改,您就已经可以使用:

package learn.javafx;import javafx.animation.Keyframe;import javafx.animation.Timeline;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.geometry.Bounds;import javafx.scene.Scene;import javafx.scene.layout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.stage.Stage;import javafx.util.Duration;public class GamePractice extends Application {    public static Circle circle;    public static Pane canvas;    @Override    public void start(final Stage primaryStage) {        canvas = new Pane();        final Scene scene = new Scene(canvas, 800, 600);        primaryStage.setTitle("Game");        primaryStage.setScene(scene);        primaryStage.show();        circle = new Circle(15, Color.BLUE);        circle.relocate(100, 100);        canvas.getChildren().addAll(circle);        final Timeline loop = new Timeline(new Keyframe(Duration.millis(10), new EventHandler<ActionEvent>() { double deltaX = 3; double deltaY = 3; @Override public void handle(final ActionEvent t) {     circle.setLayoutX(circle.getLayoutX() + deltaX);     circle.setLayoutY(circle.getLayoutY() + deltaY);     final Bounds bounds = canvas.getBoundsInLocal();     final boolean atRightBorder = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());     final boolean atLeftBorder = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());     final boolean atBottomBorder = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());     final boolean atTopBorder = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());     if (atRightBorder || atLeftBorder) {         deltaX *= -1;     }     if (atBottomBorder || atTopBorder) {         deltaY *= -1;     } }        }));        loop.setCycleCount(Timeline.INDEFINITE);        loop.play();    }    public static void main(final String[] args) {        launch(args);    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5131872.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存