【发布时间】:2013-11-30 03:12:22
【问题描述】:
我是 Javafx 的新手,我正在创建一个简单的程序。我想要实现的是让球从墙上反弹,但我还没有弄清楚如何做到这一点。另外,请随时留下有关我的代码的其他建议。
这里是源代码:
public class GamePractice extends Application {
public static Circle circle;
public static Pane canvas;
private long counter = 0;
@Override
public void start(Stage primaryStage) {
canvas = new Pane();
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);
Timeline loop = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
if (counter++ % 10 == 0)
{
circle.setLayoutX(circle.getLayoutX() + 10);
circle.setLayoutY(circle.getLayoutY() + 10);
//This is what I currently have, am I headed the right direction?
//Check X and Y for collision with the ball
if ((circle.getTranslateX() == canvas.getWidth() - 10) || (circle.getTranslateY() == canvas.getHeight() - 10)) {
//How do I make the ball bounce?
}
}
}
}));
loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
}
感谢您的帮助。
【问题讨论】:
-
不是加10,而是减10?当然,您需要一个布尔变量来确定球应该向左还是向右移动(一旦它撞到其中一堵墙就会改变)例如,如果它撞到左边的墙,设置
movingRight = true和它什么时候撞右墙,设置movingRight = false。 -
我将编写一个非常简单的示例,但不是在 JavaFX 中,只是为了让您了解如何做到这一点。然后你可以从中获取一些想法并在你的想法中使用它。
标签: java javafx-2 javafx timeline