Game Key Events: Event or Method Overload?
If you were 开发者_如何学Pythongoing to develop a game in say, Ruby, and you were provided with a game framework, would you rather act on key up/down events by overloading a method on the main window like so:
class MyGameWindow < Framework::GameWindow
def button_down(id)
case id
when UpArrow
do_something
when DownArrow
do_something
end
end
end
Or have an event class with which you can make a method and assign a handle to it, like so:
class MyGameWindow < Framework::GameWindow
def initialize
key_down.add_handler(method(:do_something))
end
def do_something
puts "blah blah"
end
end
Please give your views, which do you think would be better in a game developement area, and thanks in advance, ell.
My preference is for polling. Events (on Windows, anyway) have a nasty habit of getting lost. I've battled long and hard with key and mouse button releases getting lost, so now my preference is just to check the state of everything every tick and do set operations to note which ones are changed.
To get closer to your question, I would tend to expect that you do not want to put your input handling in your window class. Rather- create another class which does the input handling (and feed the events to it if you prefer event-driven) and then just let it do its thing. In this setup, your window receives the events but the only thing it does with them is pass them off to the set of objects that might be able to deal with them.
The problem with doing the event handling in the window is that you're then another step (or more) removed from the thing that cares about the results of the input processing. I would tend to push the input processor and the input requirer closer together in the object graph, but again- the main window doesn't really care about (most) events itself, it should just pass those things on to the objects that do.
精彩评论