April 30, 2013

A virtual joystick for Android and LibGDX

Developing games for mobile platforms always involves the problem of finding a solution for the overall game control. For game programming with LibGdx, I created a virtual joystick modeled after classic hardware devices with the following features:
  • the knob can either be snapped to fixed directions (typically 4 or 8) or is freely movable
  • separate renderer classes ease the design of an individual visual appearance
  • around the center is the unresponsive dead zone
  • an adjustable tolerance allows to ignore very small knob position changes

a virtual joystick drawn with the circle renderer

An usage example:

1.The setup:

// create a joystick at point(123, 456) with a radius of 128 pixels
VirtualJoystick joystick = new VirtualJoystick(Gdx.input, 123, 456, 128);
joystick.setYUp(800) // view height=800 pixels, bottom-left is point 0,0
joystick.setPositionCount(8); // 8 snappable positions
joystick.setDeadZone(32); // inner dead zone circle with a radius of 32 pixel

// paint joystick with simple circles
ShapeRenderer shapeRenderer = new ShapeRenderer();
joystickRenderer = new CircleJoystickRenderer(shapeRenderer);

1.1 Keep the direction vector as member which will updated by the joystick:

Vector2 joystickDirection = new Vector2();

2. Now polling the joystick's current direction in the game loop:

// update for touch pointer 0 and retrieve the current knob direction as unit vector

3. And finally rendering the joystick:


By default, created joysticks use a y-down coordinate system which requires a camera to be set up with the shape renderer, for example like this:

int viewWidth = Gdx.graphics.getWidth();
int viewHeight = Gdx.graphics.getHeight();

cam = new OrthographicCamera();
cam.setToOrtho(true, viewWidth, viewHeight);
cam.position.set(viewWidth / 2, viewHeight / 2, 0);

shapeRenderer = new ShapeRenderer();

Currently, VirtualJoystick is digital, but a modification for analog position values is not a big deal.
The virtual joystick is published under the Apache License and hosted at GitHub.


  1. I am confused by the Apache license terms. Can I take this and put it in my commercial game without the whole game being Apache licensed?

    1. Yes, you only need to include the Apache license in your game. The game can be closed or open source, commercial or free, as you like.