Game Development Reference
In-Depth Information
function update() {
var nextX = padel.x;
if (leftKeyDown) {
nextX = padel.x - 10;
if(nextX < 0){
nextX = 0;
}
}
else if (rightKeyDown) {
nextX = padel.x + 10;
if(nextX > stage.canvas.width - padel.width){
nextX = stage.canvas.width - padel.width;
}
}
padel.nextX = nextX;
}
function render() {
padel.x = padel.nextX;
}
function tick(e) {
update();
render();
stage.update();
}
To keep the movement more smooth while holding down your arrow keys, a few variables are used to store the
current direction based on what key was pressed. When you let go, you remove that value to prevent the paddle from
moving on the next update cycle. This makes for a much more fluid movement by using the update/render cycle to
move the sprites as opposed to moving them directly in the keyboard event handlers. Figure 3-5 shows the paddle
drawn and moved on the bottom of the stage.
Figure 3-5. A game paddle drawn and controlled with arrow keys
Now that some interactivity has been accomplished by user input, some output will be necessary to give your
players some feedback on how they are doing.
Search WWH ::




Custom Search