我一直在尝试使用JavaFX应用程序来点击鼠标时向右移动一个方块。我使用TranslateTransition来实现这一目标。动画看起来非常不稳定,我似乎无法弄清楚原因。这是代码:
package main;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Pane root = new Pane();
Rectangle player = new Rectangle(30,30, Color.rgb(242, 0, 0));
player.relocate(100, 100);
root.getChildren().add(player);
Scene scene = new Scene(root,1280,720);
movePlayerOnMouseClick(scene, player, createTranslateTransition(player));
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
private TranslateTransition createTranslateTransition(Rectangle o) {
final TranslateTransition transition = new TranslateTransition(Duration.seconds(1), o);
transition.setOnFinished(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent t) {
o.setX(o.getTranslateX());
o.setY(o.getTranslateY());
}
});
return transition;
}
private void movePlayerOnMouseClick(Scene scene, Rectangle o, final TranslateTransition transition){
scene.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent event) {
transition.setToX(o.getX() + 10 * Math.cos(Math.toRadians(0)));
transition.setToY(o.getY() + 10 * Math.sin(Math.toRadians(0)));
transition.playFromStart();
}
});
}
}
我正在使用Java 8.
答案 0 :(得分:1)
TranslateTransition
通过更新节点的translateX
和translateY
属性来执行动画。这些属性与x
的{{1}}和y
属性不同(首先通过查看其Rectangle
和x
属性来定位矩形,然后应用它的转变,包括翻译。)
因此,在y
处理程序中,您将使矩形跳转到转换指定的位置,之后仍然应用转换。如果要更新平移中的坐标,则应将平移添加到坐标,然后将平移设置为零:
onFinished
然后你可能只想要
transition.setOnFinished(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent t) {
o.setX(o.getX() + o.getTranslateX());
o.setY(o.getY() + o.getTranslateY());
o.setTranslateX(0);
o.setTranslateY(0);
}
});