this is an algorithm/data structure question about making different animations at the same time. For example, a ball is falling down one pixel in a millisecond, a bullet is moving 5 pixels in a ms, and a man is moving 1 pixel in 20 milliseconds. And think that there are hundreds of them together. What is the best way of putting all animations together, moving what we need to move in one function call, and removing the ones whose animation is completed? I don’t want to create a thread for each one. What I want to do is to create one thread moving all items and sleeping until an object needs to be moved.
Note: I’m using Java/Swing, printing objects and images in JPanel.
I recently did something similar in Python. I don’t know if this is the best method, but here’s what I did.
Create an abstract
Eventclass with the following public interface:tick– calculates how much time has passed since the last tick. Perform work proportional to that time span. This should be called frequently to create the illusion of smooth movement; maybe sixteen times a second or so.isDone– returns true when the Event has finished occuring.Make a subclass of Event for anything that takes more than one frame to finish. Rotating, scaling, color changing, etc. You might create a
TweenEventsubclass of Event if you want to move an image from one part of the screen to another. During eachtick, redraw the image in a position farther away from the original position, and farther towards the destination position.You can run many Events concurrently, like so: