Skip to content

Instantly share code, notes, and snippets.

@jacius
Created March 15, 2009 01:23
Show Gist options
  • Save jacius/79254 to your computer and use it in GitHub Desktop.
Save jacius/79254 to your computer and use it in GitHub Desktop.
require 'rubygame'
include Rubygame
include Rubygame::EventTriggers
# Factory method to create KeyReleaseTriggers easily.
def released( key )
return KeyReleaseTrigger.new( key )
end
class PlayerShip
include EventHandler::HasEventHandler
def initialize( input_manager )
# Add hooks to the player ship's event handler. :up gets magically changed to
# a KeyPressTrigger, and :start_moving_forward gets changed to a MethodAction.
# So, the method gets called when the event is passed to the palyer ship's #handle method.
make_magic_hooks(
:up => :start_moving_forward,
released(:up) => :stop_moving_forward
# etc.
)
# Register to receive KeyPressed and KeyReleased events.
# You could wrap this in a #register method in input_manager, if you wanted.
input_manager.append_hook(
:owner => self,
:trigger => OrTrigger.new( KeyPressTrigger.new,
KeyReleaseTrigger.new ),
# pass the events to player ship's #handle method, to be handled by the event handler
:action => MethodAction.new( :handle )
)
end
def start_moving_forward( event )
# MethodAction works with methods that take one arg (the event) or zero args,
# like stop_moving_forward below. It's up to you, if you need more info from
# the event or not.
self.moving_forward = true
end
def stop_moving_forward
self.moving_forward = false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment