提问者:小点点

我怎么能让一个多边形物体在Java脉动(像雅达利游戏《冒险》中的圣杯)


这是我在我的画组件(省略了大多数其他东西,只是属于一个叫做圣杯的项目对象的东西,带有多边形字段,if语句的显式参数对这个问题并不重要)目前,它显示为纯白色,因为我将颜色设置为所有255,但我想让它逐渐平滑地过渡到不同的颜色,而不是选通,更像脉动,但我真的不知道那叫什么。我在考虑用数组替换Color的显式参数,这些数组循环遍历数组中的数字,并以某种方式将其链接到TimerListener,但我是图形新手,所以我不确定这是否是最好的方法。

public void paintComponent(Graphics g) {
Graphics2D sprite = (Graphics2D) g;

if (chalice.getHolding() == true || roomID == chalice.getRoomDroppedIn()) {
            sprite.setColor(new Color(255, 255, 255));
            sprite.fill(chalice.getPoly());
        }
}

共1个答案

匿名用户

一些基本概念…

  • 脉动效果需要向两个方向移动,它需要淡入淡出
  • 为了知道应该应用多少“效果”,需要知道两件事。首先,整体效果需要多长时间来循环(从完全不透明到完全透明并再次返回)以及动画在循环中走了多远。

这不是一件简单的事情,有很多“有状态”的信息需要管理和维护,通常,与其他效果或实体分开进行。

在我看来,最简单的解决方案是设计某种“时间线”,沿着时间线管理关键点(关键帧),计算每个点之间的距离和它所代表的值。

退后一步。我们知道在:

  • 0%我们希望完全不透明
  • 50%我们希望完全透明
  • 100%我们希望完全不透明

上面考虑到我们想要“自动反转”动画。

使用百分比的原因是它允许我们定义任何给定持续时间的时间线,时间线将处理其余的。在可能的情况下,始终使用这样的标准化值,它使整个事情变得简单得多。

下面是一个非常简单的“时间线”概念。它有一个Duration,时间线播放的时间,关键帧,它提供时间线持续时间内的键值,以及计算时间线生命周期内特定点的特定值的方法。

此实现还提供了“自动”重放能力。也就是说,如果时间线被“结束”播放,它被指定为Duration,而不是停止,它将自动重置并考虑“结束”的时间量作为它下一个周期的一部分(整洁)

public class TimeLine {

    private Map<Float, KeyFrame> mapEvents;

    private Duration duration;
    private LocalDateTime startedAt;

    public TimeLine(Duration duration) {
        mapEvents = new TreeMap<>();
        this.duration = duration;
    }

    public void start() {
        startedAt = LocalDateTime.now();
    }
    
    public boolean isRunning() {
        return startedAt != null;
    }

    public float getValue() {
        if (startedAt == null) {
            return getValueAt(0.0f);
        }
        Duration runningTime = Duration.between(startedAt, LocalDateTime.now());
        if (runningTime.compareTo(duration) > 0) {
            runningTime = runningTime.minus(duration);
            startedAt = LocalDateTime.now().minus(runningTime);
        }
        long total = duration.toMillis();
        long remaining = duration.minus(runningTime).toMillis();
        float progress = remaining / (float) total;
        return getValueAt(progress);
    }

    public void add(float progress, float value) {
        mapEvents.put(progress, new KeyFrame(progress, value));
    }

    public float getValueAt(float progress) {

        if (progress < 0) {
            progress = 0;
        } else if (progress > 1) {
            progress = 1;
        }

        KeyFrame[] keyFrames = getKeyFramesBetween(progress);

        float max = keyFrames[1].progress - keyFrames[0].progress;
        float value = progress - keyFrames[0].progress;
        float weight = value / max;
        
        float blend = blend(keyFrames[0].getValue(), keyFrames[1].getValue(), 1f - weight);
        return blend;
    }

    public KeyFrame[] getKeyFramesBetween(float progress) {

        KeyFrame[] frames = new KeyFrame[2];
        int startAt = 0;
        Float[] keyFrames = mapEvents.keySet().toArray(new Float[mapEvents.size()]);
        while (startAt < keyFrames.length && keyFrames[startAt] <= progress) {
            startAt++;
        }

        if (startAt >= keyFrames.length) {
            startAt = keyFrames.length - 1;
        }

        frames[0] = mapEvents.get(keyFrames[startAt - 1]);
        frames[1] = mapEvents.get(keyFrames[startAt]);

        return frames;

    }

    protected float blend(float start, float end, float ratio) {
        float ir = (float) 1.0 - ratio;
        return (float) (start * ratio + end * ir);
    }

    public class KeyFrame {

        private float progress;
        private float value;

        public KeyFrame(float progress, float value) {
            this.progress = progress;
            this.value = value;
        }

        public float getProgress() {
            return progress;
        }

        public float getValue() {
            return value;
        }

        @Override
        public String toString() {
            return "KeyFrame progress = " + getProgress() + "; value = " + getValue();
        }

    }

}

设置时间线很简单…

timeLine = new TimeLine(Duration.ofSeconds(5));
timeLine.add(0.0f, 1.0f);
timeLine.add(0.5f, 0.0f);
timeLine.add(1.0f, 1.0f);

我们给出一个指定的Duration并设置关键帧值。之后,我们只需要“启动”它并根据它的播放时间从TimeLine获取当前的

对于一个看似简单的问题,这似乎需要做很多工作,但请记住,这既是动态的,也是可重用的。

它是动态的,因为您可以提供您想要的任何Duration,从而改变速度,它将“正常工作”,并且可重用,因为您可以为多个实体生成多个实例,并且它将被独立管理。

下面的示例简单地使用SwingTimer作为动画的“主循环”。在每个循环中,它向TimeLine询问“当前”值,该值简单地充当“脉动”效果的alpha值。

TimeLine类本身是足够解耦的,无论您如何建立您的“主循环”,您只需启动它运行并尽可能从中提取“当前”值…

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.TreeMap;
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 TimeLine timeLine;
        private float alpha = 0;

        public TestPane() {
            timeLine = new TimeLine(Duration.ofSeconds(5));
            timeLine.add(0.0f, 1.0f);
            timeLine.add(0.5f, 0.0f);
            timeLine.add(1.0f, 1.0f);
            Timer timer = new Timer(5, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (!timeLine.isRunning()) {
                        timeLine.start();
                    }
                    alpha = timeLine.getValue();
                    repaint();
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
            g2d.setColor(Color.RED);
            g2d.fill(new Rectangle(45, 45, 110, 110));
            g2d.dispose();

            g2d = (Graphics2D) g.create();
            g2d.setColor(getBackground());
            g2d.fill(new Rectangle(50, 50, 100, 100));
            g2d.setColor(Color.BLACK);
            g2d.draw(new Rectangle(50, 50, 100, 100));
            g2d.dispose();
        }

    }
}

我会将TimeLine绑定为指定实体的效果的一部分。这将把TimeLine绑定到特定的实体,这意味着许多实体都可以有自己的TimeLines计算不同值和效果的验证

这是一个主观问题。“可能”有一种“更简单”的方法可以完成相同的工作,但它不像这种方法那样具有可扩展性或可重用性。

动画是一个复杂的主题,试图让它在一个复杂的解决方案中工作,运行多个不同的效果和实体只会使问题复杂化

我曾考虑过使TimeLine通用的想法,以便它可用于根据所需结果生成不同值的真实性,使其成为更灵活且可重用的解决方案。

我不知道这是否是一个要求,但是如果你有一系列你想要混合的颜色,TimeLine也会在这里帮助你(你不需要那么多的持续时间)。你可以设置一系列颜色(作为关键帧),并根据动画的进度计算使用哪种颜色。

混合颜色有点麻烦,我花了很多时间试图找到一个适合我的算法,这在颜色褪色算法中得到了证明?和Java:平滑的颜色过渡