好的,动画是一个相当复杂和深入的主题,我不会在这里讨论,它还涉及很多我不太理解的数学,所以我们不会深入讨论深度或细节,有比我更好的人可以解释它,你可以在网上阅读它
首先,我们做出一些假设......
动画是随时间变化的,其中时间是可变的。缓动是(在本例中)速度随时间的变化。这意味着动画的速度对于任何给定的时间点都是可变的。
基本上,我们想要做的就是“正常化”一切。也就是说,在动画开始时,时间为 0,结束时为 1,其间的所有其他值都是这两个值之间的分数。
如果你能这样想,事情就变得容易多了。因此,根据时间线上的给定点,您可以决定应该做什么。例如,在 50% 的情况下,您应该位于起点和终点之间的中间位置
好吧,但是这一切对我们有什么帮助呢?如果我们要绘制缓入和缓出动画的图表,它看起来会像......
![BellCurve](https://i.stack.imgur.com/zcvTm.png)
其中 x 轴是时间,y 轴是速度(两个轴上的值都在 0 和 1 之间)。因此,在沿 x(时间)的任何给定点,我们应该能够计算速度。
现在,我们可以使用贝塞尔脊柱/曲线的一些数学方法来完成此操作,并计算对象在时间轴上给定点的速度。
现在,我直接从Timing Framework借用了大部分代码,但如果你真的感兴趣,你也可以看看游戏的贝塞尔曲线:教程
(注:我实际上确实写了这样的东西,然后两天后,发现计时框架已经实现了......是一个有趣的练习......)
现在,关于此实现需要注意的重要一点是,它实际上不会返回对象的速度,但它会返回沿时间线 (0-1) 的时间进度,好吧,这听起来很奇怪,但它是什么允许您做的是计算起点和终点之间的当前位置(startValue + ((endValue - startValue) * progress))
沿着时间线
我不会详细介绍这一点,因为我真的不懂数学,我只是知道如何应用它,但基本上,我们计算沿曲线的点 (x/y),我们然后将这些值标准化(0-1)以便于查找。
The interpolate
方法使用二分搜索来查找给定时间段内最接近的匹配点,然后计算该点的速度/y 位置
public class SplineInterpolator {
private final double points[];
private final List<PointUnit> normalisedCurve;
public SplineInterpolator(double x1, double y1, double x2, double y2) {
points = new double[]{ x1, y1, x2, y2 };
final List<Double> baseLengths = new ArrayList<>();
double prevX = 0;
double prevY = 0;
double cumulativeLength = 0;
for (double t = 0; t <= 1; t += 0.01) {
Point2D xy = getXY(t);
double length = cumulativeLength
+ Math.sqrt((xy.getX() - prevX) * (xy.getX() - prevX)
+ (xy.getY() - prevY) * (xy.getY() - prevY));
baseLengths.add(length);
cumulativeLength = length;
prevX = xy.getX();
prevY = xy.getY();
}
normalisedCurve = new ArrayList<>(baseLengths.size());
int index = 0;
for (double t = 0; t <= 1; t += 0.01) {
double length = baseLengths.get(index++);
double normalLength = length / cumulativeLength;
normalisedCurve.add(new PointUnit(t, normalLength));
}
}
public double interpolate(double fraction) {
int low = 1;
int high = normalisedCurve.size() - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (fraction > normalisedCurve.get(mid).getPoint()) {
low = mid + 1;
} else if (mid > 0 && fraction < normalisedCurve.get(mid - 1).getPoint()) {
high = mid - 1;
} else {
break;
}
}
/*
* The answer lies between the "mid" item and its predecessor.
*/
final PointUnit prevItem = normalisedCurve.get(mid - 1);
final double prevFraction = prevItem.getPoint();
final double prevT = prevItem.getDistance();
final PointUnit item = normalisedCurve.get(mid);
final double proportion = (fraction - prevFraction) / (item.getPoint() - prevFraction);
final double interpolatedT = prevT + (proportion * (item.getDistance() - prevT));
return getY(interpolatedT);
}
protected Point2D getXY(double t) {
final double invT = 1 - t;
final double b1 = 3 * t * invT * invT;
final double b2 = 3 * t * t * invT;
final double b3 = t * t * t;
final Point2D xy = new Point2D.Double((b1 * points[0]) + (b2 * points[2]) + b3, (b1 * points[1]) + (b2 * points[3]) + b3);
return xy;
}
protected double getY(double t) {
final double invT = 1 - t;
final double b1 = 3 * t * invT * invT;
final double b2 = 3 * t * t * invT;
final double b3 = t * t * t;
return (b1 * points[2]) + (b2 * points[3]) + b3;
}
public class PointUnit {
private final double distance;
private final double point;
public PointUnit(double distance, double point) {
this.distance = distance;
this.point = point;
}
public double getDistance() {
return distance;
}
public double getPoint() {
return point;
}
}
}
如果我们做类似的事情...
SplineInterpolator si = new SplineInterpolator(1, 0, 0, 1);
for (double t = 0; t <= 1; t += 0.1) {
System.out.println(si.interpolate(t));
}
我们得到类似...
0.0
0.011111693284790492
0.057295031944523504
0.16510933001160544
0.3208510585798438
0.4852971690762217
0.6499037832761319
0.8090819765428142
0.9286158775101805
0.9839043020410436
0.999702
好吧,现在您可能会想,“等一下,这是一个线性级数!”,但事实并非如此,如果您将其绘制成图表,您会发现前三个和后三个值非常接近,而其他值则分散不同程度地出现,这是我们的“进步”值,我们应该沿着时间线走多远
所以现在,你的头应该快要爆炸了(我的是)——这就是为什么我说,使用框架!
但你会如何使用它?这是有趣的部分,现在记住,一切都是可变的,动画的持续时间,对象随时间的速度,刻度或更新的数量,都是可变的......
这很重要,因为这就是这样的东西的力量所在!例如,如果动画由于某些外部因素而停止,则此实现能够简单地跳过这些“帧”,而不是遇到瓶颈和令人震惊。这听起来可能是一件坏事,但相信我,这都是为了欺骗眼睛“认为”某些东西正在发生变化;)
(下面大概是8fps,所以相当蹩脚)
![Animate](https://i.stack.imgur.com/HDC8T.gif)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int startAt = 0;
private int endAt;
private int x = startAt;
private Timer timer;
private SplineInterpolator splineInterpolator;
private long startTime = -1;
private long playTime = 5000; // 5 seconds
public TestPane() {
splineInterpolator = new SplineInterpolator(1, 0, 0, 1);
timer = new Timer(5, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
long duration = now - startTime;
double t = (double) duration / (double) playTime;
if (duration >= playTime) {
t = 1;
}
double progress = splineInterpolator.interpolate(t);
x = startAt + ((int) Math.round((endAt - startAt) * progress));
repaint();
}
});
timer.setInitialDelay(0);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (!timer.isRunning()) {
startTime = -1;
startAt = 0;
endAt = getWidth() - 10;
timer.start();
}
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.fillRect(x, (getHeight() / 2) - 5, 10, 10);
g2d.dispose();
}
}
public static class SplineInterpolator {
private final double points[];
private final List<PointUnit> normalisedCurve;
public SplineInterpolator(double x1, double y1, double x2, double y2) {
points = new double[]{x1, y1, x2, y2};
final List<Double> baseLengths = new ArrayList<>();
double prevX = 0;
double prevY = 0;
double cumulativeLength = 0;
for (double t = 0; t <= 1; t += 0.01) {
Point2D xy = getXY(t);
double length = cumulativeLength
+ Math.sqrt((xy.getX() - prevX) * (xy.getX() - prevX)
+ (xy.getY() - prevY) * (xy.getY() - prevY));
baseLengths.add(length);
cumulativeLength = length;
prevX = xy.getX();
prevY = xy.getY();
}
normalisedCurve = new ArrayList<>(baseLengths.size());
int index = 0;
for (double t = 0; t <= 1; t += 0.01) {
double length = baseLengths.get(index++);
double normalLength = length / cumulativeLength;
normalisedCurve.add(new PointUnit(t, normalLength));
}
}
public double interpolate(double fraction) {
int low = 1;
int high = normalisedCurve.size() - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (fraction > normalisedCurve.get(mid).getPoint()) {
low = mid + 1;
} else if (mid > 0 && fraction < normalisedCurve.get(mid - 1).getPoint()) {
high = mid - 1;
} else {
break;
}
}
/*
* The answer lies between the "mid" item and its predecessor.
*/
final PointUnit prevItem = normalisedCurve.get(mid - 1);
final double prevFraction = prevItem.getPoint();
final double prevT = prevItem.getDistance();
final PointUnit item = normalisedCurve.get(mid);
final double proportion = (fraction - prevFraction) / (item.getPoint() - prevFraction);
final double interpolatedT = prevT + (proportion * (item.getDistance() - prevT));
return getY(interpolatedT);
}
protected Point2D getXY(double t) {
final double invT = 1 - t;
final double b1 = 3 * t * invT * invT;
final double b2 = 3 * t * t * invT;
final double b3 = t * t * t;
final Point2D xy = new Point2D.Double((b1 * points[0]) + (b2 * points[2]) + b3, (b1 * points[1]) + (b2 * points[3]) + b3);
return xy;
}
protected double getY(double t) {
final double invT = 1 - t;
final double b1 = 3 * t * invT * invT;
final double b2 = 3 * t * t * invT;
final double b3 = t * t * t;
return (b1 * points[2]) + (b2 * points[3]) + b3;
}
public class PointUnit {
private final double distance;
private final double point;
public PointUnit(double distance, double point) {
this.distance = distance;
this.point = point;
}
public double getDistance() {
return distance;
}
public double getPoint() {
return point;
}
}
}
}
所以,除了SplineInterpolator
,魔法发生在里面ActionListener
为了javax.swing.Timer
(以及一些在mouseClicked
事件处理程序)
基本上,这计算了时间量(duration
)动画已经播放,这成为我们的标准化时间t
or fraction
值(0-1)在时间线上,然后我们用它来计算我们在时间线上的“进度”SplineInterpolator
并根据对象的开始位置和结束位置之差乘以当前“进度”来更新对象的位置
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
long duration = now - startTime;
double t = (double) duration / (double) playTime;
if (duration >= playTime) {
t = 1;
}
double progress = splineInterpolator.interpolate(t);
x = startAt + ((int) Math.round((endAt - startAt) * progress));
repaint();
瞧,我们有一个缓入和缓出动画!
现在,去使用动画框架吧!这真是太简单了:P
- 对于“快进/慢出”,您可以使用
0, 0, 1, 1
- 对于“慢入/快出”,您可以使用
0, 1, 0, 0
- 对于“慢速”,您可以使用
1, 0, 1, 1
- 对于“慢出”,您可以使用
0, 0, 0, 1
(或者至少这些是我使用的值)
实验看看你会得到什么