javafx简单的PathTransition动画

时间:2015-07-15 20:07:01

标签: java animation javafx path

我正在使用JavaFX来构建一个卡片游戏,我很难添加简单的动画。

我有一个HBox,里面有多个ImageView。每个图像的右边距为-80,以使图像彼此重叠。

现在我想在添加卡时为卡添加动画效果。我想将它放在屏幕上的某个位置(对手玩家手)并将其移动到没有动画的位置。

我试过了:

// Animation
Path path = new Path();
MoveTo moveTo = new MoveTo(200, 200);
moveTo.setAbsolute(true);
path.getElements().add(moveTo);
LineTo lineTo = new LineTo(0, 0);
path.getElements().add(lineTo);
PathTransition pathTransition = new PathTransition();
pathTransition.setDuration(Duration.millis(4000));
pathTransition.setPath(path);
pathTransition.setNode(imageView);
pathTransition.setCycleCount(1);
pathTransition.play();

但它不像我想要的那样有效。我不知道如何处理协调员,也无法找到解决问题的方法。

我希望有人可以帮我解决问题

1 个答案:

答案 0 :(得分:1)

正确的Path几何形状严重依赖于根Parent的布局。在下面的示例中,Path从左上角到右下角,经过调整以保持移动Rectangle在视野中。它将矩形添加到Pane,“因为除了将可调整大小的子项调整为其首选大小之外,它不执行布局。”如果您使用更高级的布局,例如StackPane,相应地调整对齐方式:

StackPane root = new StackPane();
root.setAlignment(Pos.TOP_LEFT)

image

import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

/** @see http://stackoverflow.com/a/31443755/230513 */
public class AnimationTest extends Application {

    private static final int SIZE = 256;
    private static final int RECT = SIZE / 4;
    private static final int R2 = RECT / 2;

    @Override
    public void start(Stage stage) {
        stage.setTitle("Animation Test");
        Rectangle rect = new Rectangle(0, 0, RECT, RECT);
        rect.setArcHeight(16);
        rect.setArcWidth(16);
        rect.setFill(Color.GOLD);
        Pane root = new Pane();
        root.getChildren().add(rect);
        Scene scene = new Scene(root, SIZE, SIZE);
        stage.setScene(scene);
        stage.show();

        Path path = new Path();
        path.getElements().add(new MoveTo(R2, R2));
        path.getElements().add(new LineTo(SIZE - R2, SIZE - R2));
        PathTransition pathTransition = new PathTransition();
        pathTransition.setDuration(Duration.millis(1000));
        pathTransition.setPath(path);
        pathTransition.setNode(rect);
        pathTransition.setCycleCount(Timeline.INDEFINITE);
        pathTransition.setAutoReverse(true);
        pathTransition.play();
    }

    public static void main(String[] args) {
        launch(args);
    }

}