Issue
I'm making a key shooter game in JavaFX where there are floating words moving around the screen. I want to shoot a "laser" (a elongated red rectangle) at the word once the user types the correct word. I need the x and y values of the word when the user types the correct word so I can make the rectangle travel to that position. How would I go about getting the key values?
Here is my timeline code:
final Timeline timeline = new Timeline();
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(wordTime),
new KeyValue (word.getWordBox().translateXProperty(), rand.nextInt(100, 500))));
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(wordTime),
new KeyValue (word.getWordBox().translateYProperty(), rand.nextInt(0, 150))));
wordTime is a value taken from user input that changes how long the words on the screen. word.getWordBox() is the word that moves around the screen. Please let me know if I need to restructure this question, give more detail, etc.
I tried to use
timeline.getKeyFrames().get(1).getValues()
to get the values but it just gave me the list of KeyValues which doesn't seem right. If this is right please let me know.
Solution
Probably the most convenient value to get is the location of the word in its container ("parent node"). You can do this directly with
Bounds bounds = word.getWordBox().getBoundsInParent();
and then, e.g., do
double x = bounds.getCenterX();
double y = bounds.getCenterY();
etc.
Since the boundsInParent
accounts for any transforms applied to the node, this will include the current translation applied to it by the timeline
.
Answered By - James_D
Answer Checked By - Marie Seifert (JavaFixing Admin)