Display relative bearing of joystick

edited August 2015 in How To...

I'm creating a simple radar simulation and need to display the relative bearing of a joystick cursor. I'm using the GameControlPlus library, and getting excellent results with a Logitech Extreme 3D stick. I'm just not up to speed on the trig to do this...

I'd like to be able to display the relative degree position of the joystick cursor, such at at the top of the screen it would show 0 degrees, when in the 3 o'clock position it would be 90 degree, and 6 o'clock would show 180 degrees and a 9 o'clock it would show 270... and so on. I guess the max would be 359 deg after which the bearing would become 0 again. This is relative to the center of the screen, so the Y portion (width) should have no effect on the reading.

I suspect this is fairly trivial to do, but as a Processing noob, my best efforts have failed!

Answers

  • Answer ✓

    SOLVED!

    I'm using a function called "getUserInput()" from the excellent GameControlPlus Library, where the joystick movement is reported as a range from -1 to 1.

    The code then uses a map function to convert that to 0 to width and 0 to height:

    JOYX = map(stick.getSlider("X").getValue(), -1, 1, 0, width);

    So I just added two extra lines to map the movement to two additional vars:

    cartX = map(stick.getSlider("X").getValue(), -1, 1,-90,90); cartY = map(stick.getSlider("Y").getValue(), -1, 1,90,-90);

    This gets me into a form of Cartesian coordinates, and from this it is converted to degrees, including a case for over 180 degrees:

    float actBrg() { float x, y, a=0; getUserInput(); // read joystick x = degrees(atan2(cartX, cartY)); if (x<0) x = x + 360; return x; }

    ... and Bob's your Uncle!

    May not be the most elegant or math-correct solution, but DOES get the job done.

    ;)

  • The funcion atan2 expexts the y coordinate first e.g.

    x = degrees(atan2(cartY, cartX));

    In computer graphics the angle starts at 0° along the X axis and increases clockwise. All the trig functions expect that.

  • Oops... This is the first time I used that function. Will check my math... I do need 0 degrees to be at the top of the screen as this is the bow of the ship on the radar representation. 90 degrees is the center of the starboard side...

  • x = degrees(atan2(cartY, cartX));
    if (x<0) x = x + 360;
    x = (x + 270)%360;
    

    Should do it.

Sign In or Register to comment.