我正在使用JavaFX进行应用程序,我遇到了问题。
我有一个跟随路径的动画,但我需要在n秒后暂停动画,并在其他n秒后从前一个位置继续。
代码:
public class Controller {
@FXML
ImageView img1;
@FXML
private Path road;
private PathTransition anim;
public void initialize() {
road.setStroke(Color.WHITE);
road.setStrokeWidth(4);
road.getStrokeDashArray().addAll(10.0, 10.0);
// Car 1
img1.setImage(new Image("file:src/vehicle1.png"));
img1.setX(-img1.getImage().getWidth() / 2);
img1.setY(300 - img1.getImage().getHeight());
img1.setRotate(0);
img1.setFitHeight(0);
img1.setFitWidth(0);
}
public void startRace() {
anim = new PathTransition();
anim.setNode(img1);
anim.setPath(road);
anim.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
anim.setInterpolator(Interpolator.LINEAR);
anim.setDuration(new Duration(6000));
//anim.setCycleCount(Timeline.INDEFINITE);
anim.play();
}
}
谢谢。
答案 0 :(得分:0)
使用Timeline来控制播放和暂停动画的时间。
Timeline playtime = new Timeline(
new KeyFrame(Duration.seconds(0), event -> anim.play()),
new KeyFrame(Duration.seconds(2), event -> anim.pause()),
new KeyFrame(Duration.seconds(3), event -> anim.play())
);
playtime.play();
答案 1 :(得分:0)
如果你想保留一个动画,你可以使用插值器插入“暂停”,保持值相同一段时间:
public class PauseInterpolator extends Interpolator {
private final double pauseStart;
private final double pauseEnd;
private final double rate;
private final double breakFraction;
/**
* Constructor. It's required that {@literal pauseEnd - pauseStart < 1}.
* @param pauseStart the start of the pause in interval [0.0, 1.0].
* @param pauseEnd the end of the pause in interval [0.0, 1.0]. Must be
* greater then {@literal pauseStart}.
*/
public PauseInterpolator(double pauseStart, double pauseEnd) {
if (pauseStart > pauseEnd || pauseStart < 0 || pauseEnd > 1 || (pauseEnd == 1 && pauseStart == 0) ) {
throw new IllegalArgumentException();
}
this.pauseStart = pauseStart;
this.pauseEnd = pauseEnd;
this.rate = 1 / (1 + pauseStart - pauseEnd);
this.breakFraction = this.rate * pauseStart;
}
@Override
protected double curve(double t) {
if (t < pauseStart) {
return t * rate;
} else if (t > pauseEnd) {
return breakFraction + (t - pauseEnd) * rate;
} else {
return breakFraction;
}
}
}
...
// time to pause : pause duration : time from pause to end = 1 : 1 : 1
anim.setInterpolator(new PauseInterpolator(1d/3, 2d/3));
...
请注意,这样您需要将持续时间设置为动画时间加上暂停持续时间。