1. Widgets
  2. Joystick

Widgets

Joystick

The joystick widget is interactive controller that allows users to input directional movement, commonly used in games for character or camera control. The configuration is at gmwJoystick, see gmwjoystickTheme.

You draw a joystick with gmw_joystick and provides the X and Y position values of the joystick knob.

For animated joysticks with smooth transitions, you can use gmw_joystick_anim which takes additional parameters for animation state.

Example

        #include <gama.h>

int main() {
    double joy_x = 0, joy_y = 0; // Variables to store joystick position
    double joy_x_anim, joy_y_anim; // Animation state variables

    gm_init(500, 500, "Joystick Example");

    do {
        // Draw the joystick and get its position
        int active = gmw_joystick(0, 0, 0.3, &joy_x, &joy_y);

        // Or use the animated version for smoother transitions
        // int active = gmw_joystick_anim(0, 0, 0.3, &joy_x, &joy_y, &joy_x_anim, &joy_y_anim);

        // Use the joystick values
        if(active) {
            // Joystick is being held/used
            gm_draw_text(-0.9, 0.8, "Joystick Active!", "", 0.1, GM_WHITE);
        }

        // Display current values
        char text[10];
        sprintf(text, "X: %.2f", joy_x);
        gm_draw_text(-0.9, 0.6, text, "", 0.08, GM_WHITE);
    
        sprintf(text, "Y: %.2f", joy_y);
        gm_draw_text(-0.9, 0.5, text, "", 0.08, GM_WHITE);

        // Visualize the animated joystick position (use joy_x_anim, joy_y_anim if using animated version)
        gm_draw_circle(joy_x * 0.5, joy_y * 0.5, 0.05, GM_YELLOW);

    } while(gm_yield());

    return 0;
}

      

Configuration

The joystick appearance and behavior can be customized through the gmwJoystick global variable:

        // Change the default background color
gmwJoystick.background = GM_DARK_GRAY;

// Change the knob color
gmwJoystick.knob = GM_BLUE;

// Adjust scale
gmwJoystick.scale = 1.2;

      

Tips

  • The joystick position values range from -1 to 1 in both X and Y directions
  • Use the return value to determine if the joystick is currently being manipulated
  • The third parameter of gmw_joystick controls the size of the joystick area

Reference

joystick.h reference


Previous <- Scale