如何消除动画过程中出现的闪烁?

2023-12-09

我正在通过在 JApplet 中制作一个小游戏来学习 Java。 我的精灵动画遇到了一些问题。

这是代码:

this.sprite.setBounds(0,0,20,17);

this.sprite.setIcon(this.rangerDown);
for(int i = 0; i< 16;i++)
{
    this.sprite.setBounds(this.sprite.getX(), this.sprite.getY()+1, 20, 17);
    this.sprite.update(this.sprite.getGraphics());

    try{
        Thread.currentThread().sleep(100);
    }catch(InterruptedException e){
}

}

它在动画过程中留下了一些闪烁。动画结束后,闪烁消失,但有点难看......我想我错过了一些步骤。 我使用这种方法是因为它目前可以提供更好的结果,但如果可能的话,我希望不使用 AWT,而是使用 Swing。

有什么想法可以消除闪烁吗?

谢谢阅读。

截屏(无法发布图片,抱歉)。


这不是影子。它是你的精灵的边界。它只是恰好是黑色的并且看起来像一个阴影。如果你改变精灵的移动量(比如 50 像素,而不仅仅是 1),你就会明白我的意思。

要解决这个问题,您需要做的是每次更新精灵位置时也绘制背景。尽管这可能会产生闪烁。

正确的方法是改变绘制对象的方式。您需要重写面板的paintComponent方法,然后在每次更新精灵的位置时调用repaint。

EDIT:

有关基本用法,请参阅此代码示例。注意:这不是使用线程编写动画的方式。我写这个是为了向您展示 PaintComponent 方法中的内容,并编写动画线程来向您展示您提到的“阴影”已经消失。线程中永远不要有非结束的运行循环:)

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame("Test");
        MyPanel c = new MyPanel();
        f.getContentPane().add(c);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(350, 100);
        f.setVisible(true);
    }

}

class MyPanel extends JPanel {

    int x = 0;
    boolean toTheRight = true;

    public MyPanel() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    x = (toTheRight)?x+5:x-5;
                    if (x>300)
                        toTheRight = false;
                    if (x<0)
                        toTheRight = true;
                    repaint();
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D)g.create();
        g2.setPaint(Color.white);
        g2.fillRect(0, 0, getWidth(), getHeight());
        g2.setPaint(Color.red);
        g2.fillOval(x-2, 50, 4, 4);
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何消除动画过程中出现的闪烁? 的相关文章

随机推荐