Returns whether the button id is currently pressed
Ideal when you want to keep doing something as far the key is still pressed (moving, ...)
Here is a code that contains both systems:
class MyGame < Gosu::Window
def initialize
@x = 100
@y = 100
@velocity = 3
end
def button_down(button_id)
case button_id
when Gosu::KB_ESCAPE
close
when Gosu::KB_SPACE
shoot
else
super
end
end
def update
move_left if Gosu.button_down? Gosu::KB_LEFT
move_right if Gosu.button_down? Gosu::KB_RIGHT
move_up if Gosu.button_down? Gosu::KB_UP
move_down if Gosu.button_down? Gosu::KB_DOWN
end
def shoot
puts "Shoot!"
end
def move_left
@x -= @velocity
end
def move_right
@x += @velocity
end
def move_up
@y -= @velocity
end
def move_down
@y += @velocity
end
end
There are 2 ways to detect when a button is pressend.
Using the event listener
Ideal when you want to trigger something only in the moment the button pass from released to pressed (shoot, jump, ...)
Checking is the button is down in this frame
Ideal when you want to keep doing something as far the key is still pressed (moving, ...)
Here is a code that contains both systems: