简体   繁体   English

如何使动画仅在Java中运行一次?

[英]How do I make an animation run just once in java?

So I am using the framework from a book on how to program games in java and it has an animation class like so: 因此,我正在使用一本书中的框架来编写Java编程游戏,该框架具有如下动画类:

package com.vincent.framework.animation;

import java.awt.Graphics;

public class Animation {

private Frame[] frames;
private double[] frameEndTimes;
private int currentFrameIndex = 0;

private double totalDuration;
private double currentTime;

public Animation(Frame... frames) {
    this.frames = frames;
    frameEndTimes = new double[frames.length];

    for (int i = 0; i < frames.length; i++) {
        Frame f = frames[i];
        totalDuration += f.getDuration();
        frameEndTimes[i] = totalDuration;
    }
}

public synchronized void update(float increment) {
    currentTime += increment;

    if (currentTime > totalDuration) {
        wrapAnimation();
    }

    while (currentTime > frameEndTimes[currentFrameIndex]) {
        currentFrameIndex++;
    }

}

private synchronized void wrapAnimation() {
    currentFrameIndex = 0;
    currentTime %= totalDuration;
}

public synchronized void render(Graphics g, int x, int y) {
    g.drawImage(frames[currentFrameIndex].getImage(), x, y, null);
}

public synchronized void render(Graphics g, int x, int y, int width, int height) {
    g.drawImage(frames[currentFrameIndex].getImage(), x, y, width, height, null);
}

}

That is fine if you want the animation to repeat over and over, but how can I make an animation stop when it gets to the last frame? 如果您希望动画不断重复,那很好,但是当动画到达最后一帧时,如何使动画停止? I have tried having an if statement to check if it has reached the last stage, but it would skip frames for some reason. 我尝试过使用if语句检查它是否已到达最后一个阶段,但是由于某种原因它会跳过帧。 Thanks for any help! 谢谢你的帮助!

Getting rid of the line currentFrameIndex = 0 in the method wrapAnimation() ended up working. 摆脱方法wrapAnimation()中的currentFrameIndex = 0行最终可以正常工作。 It turns out the problem was in another class where update() was being called. 事实证明,问题出在另一个调用了update()类中。 The animation timer was starting too early in some cases causing it to skip frames. 在某些情况下,动画计时器启动得太早,导致其跳过帧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM