获取JavaFX时间轴动画中对象的位置

在JavaFX应用程序中,当对象通过时间轴动画移动时,获取其当前位置对于实现诸如激光射击等互动效果至关重要。本教程将详细介绍如何获取这些动态位置信息,并提供示例代码进行演示。

获取对象在父节点坐标系中的边界

JavaFX的Node类提供了一个非常有用的方法:getBoundsInParent()。此方法返回一个Bounds对象,该对象描述了节点在其父节点坐标系中的边界。由于boundsIn

Parent属性会考虑应用于节点的所有变换(包括由时间轴动画引起的平移),因此它可以准确反映节点的当前位置。

Bounds bounds = word.getWordBox().getBoundsInParent();

在上面的代码片段中,word.getWordBox()代表屏幕上移动的单词对象。getBoundsInParent()方法返回该单词对象在其父容器中的边界。

获取中心点坐标

有了Bounds对象,就可以轻松获取单词对象的中心点坐标,这对于计算激光射击的目标位置非常有用。

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

注意事项:

  1. 确保在获取对象位置时,时间轴动画已经启动。否则,getBoundsInParent()方法可能返回初始位置,而不是动画过程中的位置。
  2. boundsInParent属性返回的是对象在其父节点坐标系中的边界。如果需要相对于屏幕的绝对位置,可能需要将其转换为屏幕坐标系。

总结

通过getBoundsInParent()方法,可以方便地获取JavaFX时间轴动画中移动对象的实时位置。这对于实现需要精确位置信息的互动效果,如激光射击游戏,至关重要。通过获取边界框,可以计算对象的中心点坐标,从而准确地定位目标位置。