The mouse buttons are handled in the same way as keyboard and gamepad buttons. You can both query them with button_down? and events with button_down and button_up. However, mouse movement may only be queried, there are no events for mouse movement. Gosu::Window's mouse_x and mouse_y methods provide the X and Y coordinates of the mouse pointer.
Note that the X and Y coordinates are relative to the game window. So, for example, if the mouse is at the top left corner, it will be near the coordinate (0,0). Also, if the mouse pointer is outside of the game window entirely, it will still report where the pointer is relative to the window. So both mouse_x and mouse_y can be less than zero and more than the width or height of the window.
The following program will display a new sprite wherever you click the mouse. Note that it uses both event-driven input (for the clicks), and query-driven input (to get the position of the mouse). A full, runnable file is available here.
class MyWindow < Gosu::Window
WIDTH = 640
HEIGHT = 480
TITLE = "Mouse Input Example"
TOP_COLOR = Gosu::Color.new(0xFF1EB1FA)
BOTTOM_COLOR = Gosu::Color.new(0xFF1D4DB5)
def initialize
super(WIDTH, HEIGHT, false)
self.caption = TITLE
@last_frame = Gosu::milliseconds
with_data('player.png') do|f|
@image = Gosu::Image.new(self, f, false)
end
@locs = []
end
def needs_cursor?; true; end
def update
calculate_delta
end
def calculate_delta
@this_frame = Gosu::milliseconds
@delta = (@this_frame - @last_frame) / 1000.0
@last_frame = @this_frame
end
def draw
draw_background
@locs.each do|l|
@image.draw(l[0], l[1], Z::Player)
end
end
def draw_background
draw_quad(
0, 0, TOP_COLOR,
WIDTH, 0, TOP_COLOR,
0, HEIGHT, BOTTOM_COLOR,
WIDTH, HEIGHT, BOTTOM_COLOR,
Z::Background
)
end
def button_down(id)
case id
when Gosu::MsLeft
@locs << [mouse_x, mouse_y]
when char_to_button_id('c')
@locs = []
end
end
end
This article is part of a series. Read more articles about Rapid Game Prototyping in Ruby


