Search code examples
javamultithreadingswinganimationswingworker

Should I be using SwingWorker, threading, or a recursive update for this animation?


As I have said in my previous questions, I'm still new to Java. I'm developing a tile-based game in Java. The movement is on a grid. I'm at the stage where I'm implementing character movement.

My plan was to use the code which I pasted in this question. However, this didn't work, and I was told I should use SwingWorker.

Being a problem solver, I've been thinking about this over the day, and I had a thought. I could achieve the same effect by doing things a bit differently.

I mentioned that I had a timer that went off every 20 milliseconds, calling a repaint.

My idea was that I could have a method call before the repaint in the event for the timer, which would move all of the people 1 unit nearer to their destination (next square/tile). Would that sort of thing work? Later on in the game, there may be 100 or so people. Would 20ms be enough time to loop through all the people and move them one unit closer to their destination? Is 20ms too short a time? Am I just making no sense at all?

Your opinions / answers / thoughts are welcome :)


Solution

  • OK, first to answer the 20 millis question. You can get quite a lot of game logic done in 20ms. But I'd say it's too frequently to be updating the display. You should also bear in mind that the OS generally dishes out CPU in the order of 10-20 ms timeslices-- in other words, another process at any moment could easily delay your process by about that amount of time. Have a look, for example, at my article on the behaviour of Thread.sleep()-- notice from the graph that as the system is moderately busy, the OS can't honour the sleep time we asked for. If you need an average sleep between frames of 100ms, then 20ms or so jitter here and there won't be too bad. But 20ms jitter when you asked for 20ms will probably be more noticeable...

    So I'd probably start at 10 frames per second (100ms pauses) and see how that looks.

    As far as the code is concerned, if your game logic will take more or less the same amount of time each tick, then I'd start with logic-repaint-sleep on each tick. Remember you need to synchronize on the things you're painting, so in your game logic thread, you ideally need to avoid holding on to locks for too long.