栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438024.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号