开发者

What are good techniques to handle state and state change in game development?

I'm an experienced developer new to game development, and I have made a reasonably simple but working 3D platformer game and am looking for ways to make the architecture more scalable.

What is a good way to handle state in game development?

A very naive approach is to have multiple booleans like:

time_stopped = True
time_slow_motion = False
level_loaded = True
level_paused = True
level_completed = False

This is very inflexible since a developer error could lead to time_stopped = True and time_slow_motion = True at the same time, which would destroy game logic.

I'm looking for a better approach in the direction of:

class TimeState:
    STOPPED = 0
    SLOW_MOTION = 1
    NORMAL = 2
    current_state = 0

    def isStopped(self):
        if current_state == self.STOPPED: return True

But how would I handle multiple groups of state in a good way? I could create a LevelState which had LOADED, PAUSED and COMPLETED states. But how do I handle overlapping groups like when LevelState and TimeState PAU开发者_如何学CSED should always be the same? Is there a good design pattern or a good practice on how to solve state management?

What is a good way to handle state change?

My thoughts are to either give the state object eg. LevelState callback functions to execute on any given state change - or to poll the state object each game loop like if level_state.changedTo() == LevelState.COMPLETED: doStuff(). Are there better ways to handle this? Message queues/events? I don't want to embed logic into the state objects.

I'm also interested in if one should handle both changedFrom and changedTo events, and what would happen if logic triggered by changedFrom changes the state of the object before the changedTo logic is triggered - who wins?

I don't want implementation/language specific answers but tips on a good way to think architecturally wise.


This is such a common thing that there is even a pattern: The State Pattern

At the start, it seems like this approach has some overhead, but as the logic gets more complicated you will see the benefits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜