Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a gif run once and stop in Java?

Basically I have a game where I want to play an explosion gif whenever the player (or an enemy) dies, but I want the gif to just play once. I have everything set up in a class and I have an ArrayList that gets explosions added to it when I need it to, and I currently have it set up to remove them once the gif's duration has been reached (using System.currentTimeMillis()). The only problem there is that it isn't exact, and sometimes the gif stops early and disappears, and sometimes it rolls over, both situations causing the next one to start where the other one left off. Is there some sort of method, class, listener of some sort, or anything I can use to tell what frame my gif is on, or how many times it has looped? My code can do the rest of the work, I just need something better to put in my if statement than this:

g2D.drawImage(explosion, x - 150, y - 150, null);
    if(System.currentTimeMillis() - startingTime > 520){
        System.out.println(System.currentTimeMillis());//for testing accuracy
        Game.explosions.remove(this);
        explosion = null;
    }
like image 311
Monkeybro10 Avatar asked Nov 30 '25 04:11

Monkeybro10


1 Answers

The usual solution to this is to not use a gif :)

Most games will store each 'frame' of the gif separately, and display them in order, instead of trying to get gif rendering to work.

System.currentTimeMillis() is not terribly accurate, plus there can be tons of stuff going on in the background between calls to your draw function (all of which affects the framerate) so I would recommend against relying on that in general.

like image 86
Kane Avatar answered Dec 02 '25 16:12

Kane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!