Keyboard Controls
Iam using the jquery plugin jquery.hotkeys plugin to add and remove handlers for keyboard events.This makes handling keyboard events across browsers much easier.
We can escape from writing code that looks like,
if (Netscape) {
use Netscape model
}
else if (Explorer) {
use Microsoft model
}
In this example, we will be adding a simple object with Texture to the HTML5 doc and make it move based on the keyboard event.
Creating an object and adding texture to it,
// object player
var player= {
color: "#00A",
x: 50,
y: 50,
width: 20,
height: 20
var player= {
color: "#00A",
x: 50,
y: 50,
width: 20,
height: 20
draw: function() {
canvas.fillStyle = this.color;
canvas.fillRect(this.x, this.y, this.width, this.height);
}
};
player.sprite = Sprite("images/player.png");
player.draw = function() {
this.sprite.draw(canvas, this.x, this.y);
};
canvas.fillStyle = this.color;
canvas.fillRect(this.x, this.y, this.width, this.height);
}
};
player.sprite = Sprite("images/player.png");
player.draw = function() {
this.sprite.draw(canvas, this.x, this.y);
};
Adding Events to the object,
function update() {
.....
// Add collision detection code here
if(keydown.left ) {
player.x -= 2;
}
if(keydown.right ) {
player.x += 2;
}
if(keydown.down ) {
player.y += 2;
}
if(keydown.up ) {
player.y -= 2;
}
....
}
p.s. JavaScript is a language. jQuery is a framework built with JavaScript to help JavaScript programmers who are doing common web tasks.