Setting up keyboard cursor keys in phaser ce.
For todays post on Phaser ce topics I thought I would put together a quick post on keyboard.createCursorKeys. This can be used to create an object containing a collection of four hot keys for up down left and right. As such this can be used as a way to quickly get going with directional movement of a display object with the keyboard in phaser. Each hot key object can be used to pull the current state of a key in an update loop, as well as attach events via Phaser.signal instances. So in this post I will be writing about how to go about getting keyboard movement up and running real quick in a phaser ce project with this method.
1 - What to know
1.1 - This is a phaser ce 2.x post
In this post I am using phaser community edition 2.11.0 of phaser.
2 - Simple example of keyboard.createCursorKeys
For a simple example of using keyboard.createCursorkeys I made a a project that involves calling a method in the update method of a state object that uses an instance of keyboard.createCursorkeys to pull the status of the arrow keys of the keyboard. The method uses the cursor keys to just move the position of a sprite and that is it.
2.1 - The moveSpriteWithCursors helper
So here is the helper method that will make use of keyboard.createCursorKeys. Here I feature test if an instance of cursor keys is present and if not create it. I then use the isDown booleans of the up, down, left, and right properties of the object that is created with createCursorKeys to poll if a key is down or not, and if so more the sprite.
In a real project I might create the instance of cursorKeys elsewhere once rather than feature test, and I would likely change physics values rather than move the sprite directly. However A method like this helps to wrap everything that is need into a nice neat little package for the sake of this simple demo.
2.2 - Create the ball sheet
Here I am just creating a sprite sheet using canvas.
2.3 - The Phaser.Game instance
Now I just need to pull everything together.
When this demo is up and running I can more the sprite around with the cursor keys of my keyboard.
3 - Conclusion
The cursor keys method is a great way to make a quick collection of Phaser key objects for the arrow keys. It is also possible to use the Phaser.Key class to make a custom collection of objects like this depending on the project. I might get around to expansing this post, or writing another one on that topic at some time soon as I expand my phaser ce content more.