rubylibgosu

Gosu, how to detect when key is pressed?


I want to move my character left and right when the player is pressing Left cursor or right cursor.

How do I detect in the update function in Gosu when a key is pressed?


Solution

  • There are 2 ways to detect when a button is pressend.

    Using the event listener

    This method is called before #update if a button is pressed while the window has focus.

    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

    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