Forums Archived

The forums are being archived. See this topic for more information.

help with magic_hooks

Get help and support with Rubygame

help with magic_hooks

Postby sparkymat » Tue Nov 03, 2009 3:48 pm

I was reading demo_rubygame.rb, to figure out how to use magic hooks. I am finding it a bit complex to follow. Is there a simple tutorial that explains just the magic hooks?
Posts: 2
Joined: Mon Mar 09, 2009 12:37 pm

Re: help with magic_hooks

Postby jacius » Wed Nov 04, 2009 8:32 pm

Hrm, I don't think there are any examples or guides yet that explain just the hooks (I really ought to write one), but hopefully it will be easy to understand with a little explanation.

There isn't really any such thing as a "magic hook", the make_magic_hooks method is just an easy way to create normal EventHooks in an EventHandler. I call it "magic" because it uses some rules of thumb to guess what you want it to do. The exact rules are describe in the method documentation. You may find this list of keyboard symbols useful when making keyboard events.

Each event hook has a trigger and an action. The trigger looks at each event and decides whether it matches the event hook. If it does match, then the action is performed. For example, one type of trigger matches when you press a keyboard key, and one type of action calls a method.

For make_magic_hooks, each hook is represented as a key/value pair in a Hash. The keys (left side) are the triggers, and the values (right side) are the actions. So for example, this code:

Code: Select all
player1.make_magic_hooks( :space => :jump )

... means that when the space bar is pressed (the trigger), "player1.jump" should be called (the action).

This code:

Code: Select all
  :mouse_left => proc{ |owner, event|  owner.move_to( event.pos ) }

... means that when the left mouse button is pressed (the trigger), that code block (Proc) should be evaluated (the action). Inside the code block, owner means player1 (because it "owns" the event hook), and event means the MousePressed event that matched the trigger. So if the mouse was clicked at the position [10, 42], the code block would have the effect of calling "player1.move_to( [10, 42] )"

Of course, the event hooks will only work if they get a chance to see the events. So, you should pass each event that occurs to the player1.handle method (which the class inherits when you do "include Rubygame::EventHandler::HasEventHandler"). So for example, you could do this:

Code: Select all
queue =

loop do
  queue.each do |event|
    player1.handle( event )

There is a lot more I could say about the event handler system (it's very flexible and extensible, and has some other nuances), but this should cover the basics, and hopefully get you started. If you have any questions, please ask. :)
User avatar
Site Admin
Posts: 131
Joined: Fri Feb 06, 2009 11:13 pm

Return to Help & Support

Who is online

Users browsing this forum: No registered users and 1 guest