The codeleap for this section may be accessed here. In this section, we will discuss a few different ways you can read in player input. Following this explanation, we will implement Keyboard Input and Mouse Input.
Subsections
01 A Word on Input
02 Keyboard Input
03 Mouse/Touch Input
Reading in player input connects the player to the game. It gives the player control over a character, and gets them properly involved. It lets the player walk, jump, defend, attack, and so on. As useful as player input is, reading player input poorly could easily break a game. With these concerns in mind, let’s take a crack at implementing input.
By default, enchant.js provides input listeners for six buttons: UP
, DOWN
, LEFT
, RIGHT
, A
, and B
. By default, the directions are bound to the arrow keys. Any of the six buttons may also be bound to any key with an ASCII value. We’ll address that later.
Let’s implement Keyboard Input in our example code. (Once again, you can access it from here.)
‘onenterframe’
function under 04.2 Keyboard Input add:
if (game.input.left && !game.input.right) {
this.tx = this.x -= moveSpeed;
}
else if (game.input.right && !game.input.left) {
this.tx = this.x += moveSpeed;
}
if (game.input.up && !game.input.down) {
this.ty = this.y -= moveSpeed;
}
else if (game.input.down && !game.input.up) {
this.ty = this.y += moveSpeed;
}
game.keybind(ASCII_VALUE, ‘BUTTON_NAME’)
, where ASCII_VALUE
is the integer value of a key and BUTTON_NAME
is a one of the button values.
game.keybind(65, 'left');
game.keybind(68, 'right');
game.keybind(87, 'up');
game.keybind(83, 'down');
W
, A
, S
, and D
. Confirm that these new key bindings work by clicking on the RUN button and testing it.
The mouse listener of enchant.js can also be used to read in touch input. This means that games written in enchant.js that depend on mouse input can also be played on mobile devices with touch input. We will implement mouse input in another sprite class.
initialize
function under 04.3 Add Tvalues, add:
this.tx = this.x;
this.ty = this.y;
onenterframe
function under 04.3 Mouse Input add:
this.x += (this.tx - this.x)/4;
this.y += (this.ty - this.y)/4;
game.rootScene.addEventListener('touchend', function(e){
player2.tx = e.x-16;
player2.ty = e.y-16;
});
touchend
. This listener returns true when a touch or click is released. Alternatively, we can use touchstart
. This listener returns true when a touch or click initially occurs, whether or not it’s been released.