Back

Joystick

In this guide we will learn how to use an external library called nipple.js to add joystick controlls for mobile platforms.

include("nipplejs.min.js");

var cube, camera;

var manager;
var direction, pressed;

function initialize()
{
	camera = scene.getObjectByName("camera");
	cube = scene.getObjectByName("cube");
	
	direction = new Vector2(0, 0);
	pressed = false;
	
	manager = nipplejs.create(
	{
		zone: program.division,
		multitouch: false,
		maxNumberOfNipples: 1,
		mode: "dynamic"
	});
	
	manager.on("added", function(event, nipple)
	{
		nipple.on("move start end", function(event, data)
		{
			if(event.type === "move")
			{
				var force = 0.08 * data.force;
				
				direction.x = Math.cos(data.angle.radian) * force;
				direction.y = Math.sin(data.angle.radian) * force;
			}
			else if(event.type === "start")
			{
				pressed = true;
			}
			else if(event.type === "end")
			{
				pressed = false;
			}
		});
	});

	manager.on("removed", function(event, nipple)
	{
		nipple.off("move start end");
	});
}

function update()
{
	//If the joystick is pressed update position
	if(pressed)
	{
		cube.position.x += direction.x;
		cube.position.y += direction.y;		
	}
	
	//Limit the square movement
	if(cube.position.x > camera.right) cube.position.x = camera.right;
	if(cube.position.x < camera.left) cube.position.x = camera.left;
	if(cube.position.y > camera.top) cube.position.y = camera.top;
	if(cube.position.y < camera.bottom) cube.position.y = camera.bottom;
}

function dispose()
{
	manager.destroy();
}

To try this example in the editor you can download the project file or open it on the Web Editor.