How to Create a Virtual Joystick for Your HTML5 Game
Many touch-based HTML5 games use a virtual joystick mechanism. The user touches the screen to begin input, and then swipes to provide input. Swiping to the left is read just like moving a joystick to the left. The farther the user swipes, the larger the input value is. The simpleGame library has a virtual joystick object that makes it easy to implement a virtual joystick on your touch-based devices.
The virtual joystick works by returning numeric data. It’s often easiest to understand how it works by looking at the numeric output before mapping it to a visual element.
The virtual joystick is quite easy to use:
Create a variable for the joystick.
You can call it joystick. Kind of catchy.
Create the joystick if possible.
Use the game.touchable property to determine if a touch interface is present. If not, send a message to the user.
Get the mouse position.
When the virtual Joystick object detects a touch on the screen, it triggers mouseX and mouseY values. Use the joystick’s getMouseX() and getMouseY() methods to determine the X and Y positions of the touch. In this way, the touch interface acts much like the traditional mouse.
Get a diffX and diffY reading from the joystick.
When the user touches the screen, the library tracks the coordinates of the initial touch. It then measures how far away the user has swiped. The difference in X is called diffX, and the difference in Y is called diffY. Use the getDiffX() and getDiffY() methods of the virtual joystick object to determine how many pixels in X and Y the user has moved since touching the screen.
Display the current values.
For this first pass, it’s important to understand what the joystick is displaying, so just take the values and print them to an onscreen output.
Of course, the point of a virtual joystick is to move stuff around on the screen.
Here’s the code:
This example is even simpler than the previous one.
Create a simple ball sprite.
For this example, a simple ball is used. Create it like any other basic sprite.
Build a joystick object.
Make a virtual joystick object.
Map the joystick’s diffX and diffY to the ball’s dx and dy values.
This gives extremely sensitive motion, so you might want to adjust the sensitivity by dividing the diffX and diffY by some scaling factor.