HTML and CSS Reference
In-Depth Information
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
ball = new Ball(),
vx = 0,
ax = 0;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
window.addEventListener('keydown', function (event) {
if (event.keyCode === 37) { //left
ax = -0.1;
} else if (event.keyCode === 39) { //right
ax = 0.1;
}
}, false);
window.addEventListener('keyup', function () {
ax = 0;
}, false);
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
vx += ax;
ball.x += vx;
ball.draw(context);
}());
};
</script>
</body>
</html>
In this example, you simply check whether either the left or right cursor key is down. If the left cursor key is
down, you set ax to a negative value. If the right cursor key is down, make it positive. If neither is down,
set it to zero. In the drawFrame function, the velocity is added to the position just like before.
Test the example. You see that you don't have complete control over the speed of the object. You can't
stop it on a dime, so to speak. You can only slow it down to the point it stops. And if you slow it down too
much, it starts going in the opposite direction. See whether you can stop it before it hits the edge of the
canvas element.
I'm sure some game ideas are already popping into your head. Hold on to them because you're about to
expand your mastery of this technique many times over.
Acceleration on two axes
As with velocity, you can have acceleration on the x axis and y axis at the same time. You set up an
acceleration value for each axis (we usually use the variable names ax and ay ), add those to vx and vy ,
and finally add vx and vy to the x and y properties.
 
Search WWH ::




Custom Search