PC Games typically offer multiple different control mechanisms and arcade shooters especially are often better played with game pad / controller. In this quest you will add support to play your game with an Xbox 360 Controller (Windows) or PS4 Controller (macOS).

Task Definition

In order to achieve this task, you should use Phaser’s gamepad support (game.input.gamepad) in your game’s update loop. If you detect that a gamepad is detected, then you should check whether certain buttons are pressed and react to them in your game to allow the player to move their ship and fire their weapons. For added style, you could also allow the user to press a button on the controller to start the game.

Hints

The following code snippets use Phaser’s built in gamepad support to detect whether a controller is detected. If you need to do this check anywhere, then it’s good practice to do it every frame incase the user adds or removes their gamepad during gameplay.

pad1 = game.input.gamepad.pad1;

if (game.input.gamepad.supported && game.input.gamepad.active && pad1.connected)
{
	// Controller Available
}

Once you have established that the user has a game controller connected, you can check each frame (otherwise known as ‘polling’) whether or not the player is pressing any buttons. An example of detecting whether the user is pressing “LEFT” on the DPAD or the left Joystick follows.

if (pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_LEFT) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.1)
{
	// User is pressing 'left'
}

If you want to add controller support on the title screen too, then the same technique should work there too. Note. If you want to get really fancy, you could also show different text on the title screen if a controller is connected (“Press ‘A’ to Start”) instead the default message.

Sample Solution

Click on the button below to see an example solution for the sample project.

mainGameState.create = function() {
	this.gamepad = game.input.gamepad.pad1;
}

mainGameState.update = function() {
	if (this.gamepad.isDown(Phaser.Gamepad.XBOX360_DPAD_LEFT) || 
		this.gamepad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.1)) {
		this.playerShip.body.x -= 2;
	}

	if (this.gamepad.isDown(Phaser.Gamepad.XBOX360_BUTTON_A)) {
		fireBullet();
	}
}