所以我希望能够通过改变持续时间来改变动画的速度。我知道 Java 文档说这是不可能完成的,但我认为停止动画、更改持续时间并从停止点开始没有任何问题。通过这个实现,我的圆圈就停止了,并且不想再移动。我能以某种方式做到吗?如果我不能,我怎样才能制作一个可变速度的动画?
编辑: 它确实有效,但是当我更改持续时间时,起点会发生变化,而终点不会发生变化,因此它会越来越接近终点,直到停止(除非我只在圆接近时改变速度)初始起点)。对于仅影响动画速度的算法有什么想法吗?
public void initialize() {
TranslateTransition transition = new TranslateTransition();
transition.setDuration(Duration.seconds(2));
transition.setToX(162);
transition.setToY(72);
transition.setAutoReverse(true);
transition.setCycleCount(TranslateTransition.INDEFINITE);
transition.setNode(myCircle);
transition.play();
mySlider.valueProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue arg0, Object arg1, Object arg2) {
transition.stop();
Duration d = transition.getDuration();
transition.setDuration(Duration.seconds(mySlider.getValue()));
transition.playFrom(d);
System.out.println(mySlider.getValue());
}
});
}
最佳答案
EDIT: It actually works, but when I change the Duration, then the starting point changes, and the ending point doesn't so it gets closer and closer to the ending point until it stops (unless I only change the speed when the circle is close to initial starting point).
由于您没有指定 translateX
和 translateY
的起始值,TranslateTransition
会在转换时获取这些属性的当前值从停止状态到另一个状态。由于您确实停止了转换,因此 slider 的每次更改都会发生这种情况。此时翻译属性的值可能与起始位置不同。
此外,如果您减小持续时间 slider 的值,则传递给 playFrom
方法的时间可能会在循环结束之后。
我建议修改rate
property相反:
TranslateTransition transition = new TranslateTransition();
transition.setDuration(Duration.seconds(1));
...
transition.rateProperty().bind(Bindings.divide(1d, mySlider.valueProperty()));
关于Java FX TranslateTransition 持续时间更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203717/