我正在尝试在 JavaFX 中创建动画。
虽然我很难理解一种方法。
谁能解释一下底部的插值方法到底做了什么?
更具体地说,它如何使用模数?
import javafx.animation.Interpolator;
import javafx.animation.Transition;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.ImageView;
import javafx.util.Duration;
public class SpriteAnimation extends Transition {
private ImageView imageView;
private int count;
private int columns;
private int offsetX;
private int offsetY;
private int width;
private int height;
private int lastIndex;
public SpriteAnimation(
ImageView imageView,
Duration duration,
int count, int columns,
int offsetX, int offsetY,
int width, int height) {
this.imageView = imageView;
this.count = count;
this.columns = columns;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.width = width;
this.height = height;
setCycleDuration(duration);
setInterpolator(Interpolator.LINEAR);
}
protected void interpolate(double k) {
//
int index = Math.min((int) Math.floor(k * count), count - 1);
if (index != lastIndex) {
int x = (index % columns) * width + offsetX;
int y = (index / columns) * height + offsetY;
imageView.setViewport(new Rectangle2D(x, y, width, height));
lastIndex = index;
}
}
}
最佳答案
当转换运行时,k
的不同值将传递给 interpolate
。在动画开始时 0.0
将传递给 k
,在动画结束时将传递 1.0
。
int index = Math.min((int) Math.floor(k * count), count - 1);
计算 0
到 count-1
范围内的 index
。顺便说一句:我更喜欢 (int) (k * count)
而不是 (int) Math.floor(k * count)
,因为转换为 int
无论如何都会截断浮点值。
在索引发生变化时,ImageView
应该显示的图像部分被修改为显示图像的适当部分。在这里,您从左到右逐行遍历 Sprite 。
index % columns
是index
除以columns
的其余部分。这意味着 index
每增加 1,结果将增加 1,直到达到 columns
;在这种情况下,它会从 0 开始。
由于这个属性,它可以用来确定要显示的图像的水平位置。您只需乘以 Sprite 的宽度即可获得左侧的 x 坐标。
index / columns
是index
除以columns
没有休息,即index/columns
和(index - index % columns)/columns
产生相同的值。每向 index
添加 columns
,结果增加 1;当 index % column
从 0
开始时,它增加 1。因此可以用来确定 Sprite 的y坐标;您只需乘以 Sprite 的高度即可。
columns = 3
的例子
index | index % 3 | index / 3
--------------------------------------
0 | 0 | 0
1 | 1 | 0
2 | 2 | 0
3 | 0 | 1
4 | 1 | 1
5 | 2 | 1
6 | 0 | 2
...
31 | 1 | 10
这样你就可以按照以下顺序遍历 Sprite
-------------------
| 1 | 2 | 3 |
-------------------
| 4 | 5 | 6 |
-------------------
...
-------------------
| 31 | 32 | |
-------------------
关于java - 了解javafx中的插值方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40297212/