
在JavaFX应用程序中,当对象通过时间轴动画移动时,获取其当前位置对于实现诸如激光射击等互动效果至关重要。本教程将详细介绍如何获取这些动态位置信息,并提供示例代码进行演示。
JavaFX的Node类提供了一个非常有用的方法:getBoundsInParent()。此方法返回一个Bounds对象,该对象描述了节点在其父节点坐标系中的边界。由于boundsInParent属性会考虑应用于节点的所有变换(包括由时间轴动画引起的平移),因此它可以准确反映节点的当前位置。
Bounds bounds = word.getWordBox().getBoundsInParent();
在上面的代码片段中,word.getWordBox()代表屏幕上移动的单词对象。getBoundsInParent()方法返回该单词对象在其父容器中的边界。
有了Bounds对象,就可以轻松获取单词对象的中心点坐标,这对于计算激光射击的目标位置非常有用。
立即学习“Java免费学习笔记(深入)”;
double x = bounds.getCenterX(); double y = bounds.getCenterY();
getCenterX()和getCenterY()方法分别返回Bounds对象中心点的x和y坐标。这些坐标值代表了单词对象在父节点坐标系中的当前位置。
以下是一个完整的示例,展示了如何结合时间轴动画和getBoundsInParent()方法来获取移动对象的位置:
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.geometry.Bounds;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
import javafx.scene.text.Text;
import javafx.scene.paint.Color;
import java.util.Random;
public class MovingWordExample extends Pane {
private Text word;
private Rectangle laser;
private Random rand = new Random();
public MovingWordExample() {
word = new Text("Example");
word.setX(50);
word.setY(50);
getChildren().add(word);
laser = new Rectangle(0, 0, 10, 5); // 激光初始位置和大小
laser.setFill(Color.RED);
getChildren().add(laser);
startAnimation();
}
private void startAnimation() {
int wordTime = 2000; // 动画持续时间
Timeline timeline = new Timeline();
timeline.getKeyFrames().addAll(
new KeyFrame(Duration.millis(wordTime),
new KeyValue(word.translateXProperty(), rand.nextInt(100, 500))),
new KeyFrame(Duration.millis(wordTime),
new KeyValue(word.translateYProperty(), rand.nextInt(0, 150)))
);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
// 模拟用户输入正确单词后,移动激光到单词位置
setOnMouseClicked(event -> {
Bounds bounds = word.getBoundsInParent();
double x = bounds.getCenterX();
double y = bounds.getCenterY();
// 将激光移动到单词位置
laser.setTranslateX(x);
laser.setTranslateY(y);
});
}
public static void main(String[] args) {
javafx.application.Application.launch(args);
}
}注意事项:
通过getBoundsInParent()方法,可以方便地获取JavaFX时间轴动画中移动对象的实时位置。这对于实现需要精确位置信息的互动效果,如激光射击游戏,至关重要。通过获取边界框,可以计算对象的中心点坐标,从而准确地定位目标位置。
以上就是获取JavaFX时间轴动画中对象的位置的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号