我正在使用JavaFX和AnimationTimer来使圆圈移动到通过单击圆圈触发的随机位置。我看到的问题是圆圈不会朝屏幕的右上角或右下角移动,我不确定为什么。
这是我的代码:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.layout.*;
import javafx.scene.shape.*;
import javafx.stage.*;
import javafx.scene.paint.*;
import java.util.*;
import javafx.scene.*;
import javafx.animation.AnimationTimer;
public class MovingCircle extends Application {
double WIDTH = 800;
double HEIGHT = WIDTH;
class TheCircle extends Circle {
public TheCircle(){
super();
setFill(Color.GREEN);
setCenterX(WIDTH / 2);setCenterY(HEIGHT / 2);
setRadius(50);
setOnMouseClicked(event -> {
double newX = random(50, HEIGHT - 50); double newY = random(50, WIDTH - 50);
move(newX, newY);
});
}
void move(double newX, double newY){
double xVelocity;
double yVelocity;
if (newX == getCenterX()){
xVelocity = 0;
}else {
xVelocity = getCenterX() < newX ? 1 : -1;
}
if (newY == getCenterY()){
yVelocity = 0;
}else {
yVelocity = getCenterY() < newY ? 1 : -1;
}
AnimationTimer h = new AnimationTimer() {
@Override
public void handle(long l) {
setCenterY(getCenterX() + xVelocity);
setCenterX(getCenterY() + yVelocity);
//System.out.println(getCenterX() + ", " + getCenterY() + " ; " + newX + ", " + newY);
if (getCenterX() == newX && getCenterY() == newY){
this.stop();
}
}
};
System.out.println("begin!");
h.start();
}
}
public void start(Stage stage){
Pane root = new Pane();
TheCircle mover = new TheCircle();
root.getChildren().add(mover);
stage.setScene(new Scene(root, WIDTH, HEIGHT));
stage.show();
}
public static void main(String[] args){
launch(args);
}
double random(double min, double max){
return Math.floor(Math.random() * (max - min + 1) + min);
}
}
看来,如果我强迫xVelocity
和yVelocity
使圆朝这些区域设置动画,则圆要么停滞不前,要么窗口冻结。我该如何解决这个问题?