java - 如何使用线程实现缓动功能

标签 java eclipse

我正在尝试找到一种有效,正常或简单的方法来在我的Java程序中实现缓动功能。我已经启用了缓动功能,但是我觉得有一种更有效的方法可以实现。我看不到的那一个,可能是因为隧道视力。这是我的代码;有人可以向我展示我应该做些什么,或为我指明进行研究的方向

public class slide extends JPanel implements Runnable {

    Thread ease = new Thread(this);
    float total = 0;
    float dur;

    slide() {

        ease.start();
        setLayout(null);

    }

    public float calc(float t, float b, float c, float d) {

        return c * t / d + b;

    }

    public void run() {
        while (true) {
            try {
                if (total < 50) {
                    total += 1;
                } else {
                    ease.stop();
                }
                setBounds(400, Math.round(200 * total / 50 + 0), 250, 150);
                repaint();
                System.out.println(total + " " + dur);
                ease.sleep(10);
            } catch (Exception e) {
            }
        }

    }
}


我尝试为在线发现的线性缓动函数实现calc()方法,但是它几乎没有用,因为我被迫除非将方程式直接插入到其中就无法使它起作用。

最佳答案

好的,动画是一个相当复杂且深入的主题,在此不做介绍,它还涉及很多我不太了解的数学,因此我们不做大量介绍深度或细节,比我更好的人可以解释它,您可以在网络上阅读它

首先,我们做一些假设...

动画是时间的变化,其中时间是可变的。缓动是(在这种情况下)速度随时间的变化。这意味着动画的速度对于任何给定的时间点都是可变的。

基本上,我们要做的是对所有内容进行“标准化”。也就是说,在动画开始时,时间为0,在结束时为1,介于两者之间的所有其他值都是这两个值之间的分数。

如果您可以这样想,事情就会变得容易得多。因此,根据时间轴上的给定点,您可以决定应该做什么。例如,在50%的时间里,您应该位于起点和终点之间的中间位置

好的,但是这对我们有什么帮助?如果我们要绘制一个缓入缓出动画的图形,它看起来就像...



其中x轴是时间,y轴是速度(两个轴的0和1之间)。因此,在x上的任何给定点上(及时),我们应该能够计算出速度。

现在,我们可以使用贝塞尔曲线脊线/曲线进行一些数学运算,并在时间轴上给定点计算对象的速度。

现在,我直接从Timing Framework借用了大多数代码,但是如果您真的感兴趣,还可以查看Bézier Curves for your Games: A Tutorial

(nb:我实际上确实写过这样的内容,然后两天后,发现Timing Framework已经实现了……是一个有趣的练习……)

现在,关于此实现的重要说明是,它实际上不会返回您物体的速度,但是它将沿时间轴(0-1)返回时间的进展,好吧,这听起来很奇怪,但是它是什么确实允许您做的是沿着时间线计算起点和终点(startValue + ((endValue - startValue) * progress))之间的当前位置

我不会对此进行详细介绍,因为我真的不懂数学,我只是知道如何应用它,但是基本上,我们计算曲线上的点(x / y),然后将这些值归一化(0-1),以便于查找。

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,因此非常糟糕)



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之外,魔术发生在ActionListenerjavax.swing.Timer内部(还有一些在mouseClicked事件处理程序中)

基本上,这会计算动画的播放时间(duration),这将成为我们在时间轴上的标准化时间tfraction值(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


(或至少这些是我使用的值)

做实验,看看你得到什么

关于java - 如何使用线程实现缓动功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335787/

相关文章:

java - java 文本字段和文本区域的 float 输入

java - Hibernate/SQLite - 找不到 org/hibernate/dialect/unique/UniqueDelegate

java - 无法将 Maven 依赖项添加到我的 Eclipse Web 部署程序集中

javascript - 将 CoffeeScript 与 Eclipse 集成?

java - Tomcat(即服务)是否不为 Java Web 应用程序加载 native 库?

java - 如何在单击按钮等事件后自动重绘?

java - 如何在Java中正确删除数组

java - 如何从集合中删除长度为 5 的字符串?

java - 是否可以将输出缓冲到 Log4j Mail Appender?

android - 找不到 *.apk 错误