I’m writing a game and trying to think of a good way to handle complex scripted animation.
Right now the main game loop looks like:
while (true)
{
for (LevelObject obj: levelObjects)
{
obj.performGameLogic();
}
drawLevel();
}
Right now performGameLogic() is hard coded per object and does something simple like cause the game object to slowly walk back and forth while updating the sprite animation. However, I’d like to do something more complex. It would be nice if I could write something like:
class Monster extends GameObject
{
public void performGameLogic()
{
takeStep(Direction.DOWN);
takeStep(Direction.LEFT);
if (chest5.isClosed())
{
chest5.openChest();
}
playAnimation("BeatChest");
}
}
The trouble with this is that most of the above commands will require several hundred milliseconds to complete (and animate). They should also play sequentially - one after the other. However, the main thread needs to return almost immediately to perform the rest of the game logic and draw the level.
It would be better if I could somehow encapsulate this in a ‘thread’. Each time performGameLogic() was called, it would advance this ‘thread’ as far as it could and then return. (Ie, the ‘thread’ would run until it blocks, waiting for time to have elapsed or some state to be set.) When performGameLogic() was called again, the ‘thread’ would pick up again from where it left off and run until it blocks again.
Using real threads to do this would be expensive. I was wondering if there might be some clever way to create this thread-like behavior with arbitrary code.
(At the moment, I have a solution where I create Animation objects and link them together. Each Animation has an advanceLogic() method that is called to advance its state and which will fire an event when it completes. A listener will then detect this event and schedule the next Animation object. While this works, it is tedious and unintuitive.)