java - 我在 JavaFX 中为这个圆圈设置动画时遇到了问题
问题描述
我正在使用 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
使圆圈朝着这些区域设置动画,那么圆圈要么停止,要么窗口冻结。我该如何解决这个问题?
解决方案
推荐阅读
- npm - 如何让 npm 使用来自本地 libsass-dev(由 apt 安装)的 sass 而不是下载自己的包?
- python-3.x - 使用 python 脚本安装程序
- php - MySQL 查询以防止嵌套树
- git - 替换图像或文本时的语义提交类型?
- javascript - 使用谷歌应用脚本返回多次出现的值
- docker - Jenkins Job 如何将 docker 映像提升到下一个环境
- python - 如何用 Beautifulsoup 处理嵌套的 html 表?
- css - 如何覆盖背景图像上的导航栏?
- c# - EF 与数据库上的字段失去连接
- asp.net - 为什么我在尝试通过 HTTPS 访问 apple-touch-icon.png 时收到错误 403,但在浏览器中进行测试时会出现 200?