使动画更流畅

时间:2019-01-27 22:27:03

标签: java animation paintcomponent

我正在尝试使用JPanel和painComponent创建一些动画(每次按下键时都会运行的男孩)。 因此,首先,我声明一些图像,图像数组和一些绘制方法。我创建了计时器并将其添加到构造函数中。

Image img1;
Image img2;
Image img3;
Image img4;

int index = 0;

Image currentImage l;
Image[] images = new Image[4]

public class Animation extends JPanel implements ActionListener
{

    public Animation()
    {
     loadImages();
     getTimer();
     imgAdder();
     addFirstImage();
    }

    public void serCurrentImage(Image currentImage)
  {
     this.currentImage = currentImage;
   }
     public void getTimer()
   {
     Timer timer = new Timer(20,this)
      timer.start();
   }
     public void imgAdder()
   {
     images[1] = img1;
        ...
   }
     public void addFirstImage()
   {
      currentImage = img1;
   }
      private void loadImages()
   {
       try
   {
      BufferedImage img = ImageIO.read(getClass.getResource(“/resources/images/img1.png”);
      img1 = img;
      // and so on for every image
    }catch(IOexception ioe )
     ioe.printStackTrace();
    }
  }
     public void paintComponent (Graphics g)
     {
           super.paintComponent(g);
           g.drewImage(currentImage,0,0,this);
           requestsFocus();
      }
            public class FieldKeyListener extends KeyAdapter
    {
            public void move()
      {
            setCurrentImage(image[index]);
             index++;
             if( index == 4 )
                      index = 0;
       }
             public void keyPressed(KeyEvent e)
       {
             super.keyPressed(e);
             int key = e.getKeyCode();
             if(key == Key.Event.VK_LEFT)
             move();
       }
     }
}

然后使用循环为我的数组通过paintComponent绘制所有图像。 我也声明了扩展KeyAdapter的类。 一切似乎都很好,我的动画也可以工作,但是问题是它的工作不如我所愿。当我按住键时,图像变化太快,过程看起来不自然。例如,我想每秒更改3或4张图像,而不是20张。 我可以用错误的方法添加计时器吗?可能会有一些时间延迟。我不知道它是如何工作的,我不应该提及哪个监听器作为计时器中的参数。 P.s.我只是新手,我的代码在编码标准方面可能看起来不正确。我也只写了项目中代表问题的关键部分。我希望你能帮助我。预先感谢。

1 个答案:

答案 0 :(得分:1)

动画是一门复杂的学科,具有许多无聊的理论。基本上,动画是随着时间变化的幻觉。这非常重要,因为您在动画中所做的一切都会基于时间。

在类似游戏的游戏中,您将拥有许多实体,它们以不同的时间速率进行游戏。挑战之一是花时间设计一种解决方案,该解决方案允许实体在与刷新周期(即帧数)分离的状态下播放一段时间,除非您拥有具有正确帧数的子画面来进行刷新周期,但即使如此,我仍会担心,因为系统的灵活性不足以适应OS和硬件无法跟上的情况。

下面是一个简单的示例,该示例获取一张精灵表(一系列图像存储在一个图像中),期望的图像/帧数以及完成一个完整周期的时间。

它计算单个帧的大小,并根据子画面被激活的时间返回帧...

public class Sprite {

    private BufferedImage source;
    private int imageCount;
    private int imageWidth;

    // How long it takes to play a full cycle
    private Duration duration;
    // When the last cycle was started
    private Instant startedAt;

    public Sprite(BufferedImage source, int imageCount, int cycleTimeInSeconds) throws IOException {
        this.source = source;
        this.imageCount = imageCount;
        imageWidth = source.getWidth() / imageCount;
        duration = Duration.ofSeconds(cycleTimeInSeconds);
    }

    public BufferedImage getFrame() {
        if (startedAt == null) {
            startedAt = Instant.now();
        }
        Duration timePlayed = Duration.between(startedAt, Instant.now());
        double progress = timePlayed.toMillis() / (double)duration.toMillis();
        if (progress > 1.0) {
            progress = 1.0;
            startedAt = Instant.now();
        }
        int frame = Math.min((int)(imageCount * progress), imageCount - 1);
        return getImageAt(frame);
    }

    protected BufferedImage getImageAt(int index) {
        if (index < 0 || index >= imageCount) {
            return null;
        }
        int xOffset = imageWidth * index;
        return source.getSubimage(xOffset, 0, imageWidth, source.getHeight());
    }

}

nb:它也需要一种重置或停止的方式,因此您可以将精灵强制重新开始,但我将留给您

接下来,我们需要一些播放动画的方法

public class TestPane extends JPanel {

    private Sprite sprite;

    public TestPane(Sprite sprite) {
        this.sprite = sprite;
        Timer timer = new Timer(5, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                repaint();
            }
        });
        timer.start();
    }

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

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        BufferedImage img = sprite.getFrame();
        int x = (getWidth() - img.getWidth()) / 2;
        int y = (getHeight() - img.getHeight()) / 2;
        g2d.drawImage(img, x, y, this);
        g2d.dispose();
    }

}

这里没有什么特别的,它是一个简单的Swing Timer,设置为高分辨率(5毫秒),可以不断更新UI,从Sprite请求下一帧并对其进行绘制。

这里重要的部分是子画面和刷新周期是独立的。想要角色走得更快,更改精灵持续时间,想要角色走得更慢,更改精灵持续时间,不需要更改刷新周期(或任何其他实体)

所以,从...开始...

Sprite Sheet

相同的周期,第一次超过1秒,第二次超过5秒

Fastwalk SlowWalk

您还可以查看类似How to create a usable KeyReleased method in java之类的内容,它演示了如何使用键绑定和集中的Set作为“操作”存储库

相关问题