1. Computing

Mouse and Keyboard Input in Gosu

By

4 of 5

Querying Input
Mouse and Keyboard Input in Gosu

If event-based input is not your style, you can query any Gosu::Window to see if any button or key is pressed, at any time. You can ignore the button_down and button_up callbacks entirely.

To query the Gosu::Window to see if a key is pressed, call the button_down? method with the id of the button you'd like to check. Don't forget the question mark in this call! If you call button_down(Gosu::KbLeft), you'll be reporting a button press to the Gosu::Window subclass. Even if you don't have any callback methods defined, the parent class, Gosu::Window will. There will be no error, it just won't work as you expect. Just don't forget that question mark!

Here is the Player class re-written to use button_down? instead of events. A full, runnable example is available here. This time, input is checked for at the beginning of the update method. You'll also notice that this example is shorter but, in my opinion, less elegant.


class Player
  attr_reader :x, :y

  # 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)
    @direction = 0

    if @window.button_down?(Gosu::KbLeft)
      @direction -= 1
    end

    if @window.button_down?(Gosu::KbRight)
      @direction += 1
    end

    @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
end

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

©2014 About.com. All rights reserved.