1. Computing

Mouse and Keyboard Input in Gosu

By

3 of 5

Event-Oriented Input
Mouse and Keyboard Input in Gosu

Input events are delivered to the Gosu::Window instance. In the main loop, before update is called, Gosu will deliver events for all buttons that have either been pressed or released. It does this by calling the button_down and button_up methods, passing the id of the key or button pressed.

In the button_down and button_up methods, you often find a case statement. This, beside being very function, provides a very elegant and expressive way to decide what to do depending on which button was pressed or released. The following is a short example of what a button_down method can look like. It should be placed in your Gosu::Window subclass, and will close the window (ending the program) when the escape key is pressed.


def button_down(id)
 case id
 when Gosu::KbEscape
   close
 end
end

Easy, right? Let's expand this. Here is a Player class. It can move left and right if the left and right keys are pressed. Note that this class also has button_down and button_up methods. They work just like the methods from a Gosu::Window subclass. Gosu doesn't know anything about Player though, we'll be calling the Player's methods manually from the Gosu::Window's methods. A full, runnable example can be found here.


class Player
  # In pixels/second
  SPEED = 200

  def self.load(window)
    with_data('player.png') do|f|
      @@image = Gosu::Image.new(window, f, false)
    end
  end

  def initialize(window)
    @window = window
    @x = (@window.width / 2) - (@@image.width / 2)
    @y = @window.height - @@image.height
    @direction = 0
  end

  def update(delta)
    @x += @direction * SPEED * delta

    @x = 0 if @x < 0
    if @x > @window.width - @@image.width
      @x = @window.width - @@image.width
    end
  end

  def draw
    @@image.draw(@x, @y, Z::Player)
  end

  def button_down(id)
    case id
    when Gosu::KbLeft
      @direction -= 1
    when Gosu::KbRight
      @direction += 1
    end
  end

  def button_up(id)
    case id
    when Gosu::KbLeft
      @direction += 1
    when Gosu::KbRight
      @direction -= 1
    end
  end
end

This article is part of a series. Read more articles about Rapid Game Prototyping in Ruby

©2014 About.com. All rights reserved.