HTML and CSS Reference
In-Depth Information
It's easy to adapt the previous example to work with the y axis as well. You need to add the following:
The ay and vy variables
Checks for the up and down cursor keys
The right acceleration to the right velocity
Velocity to the corresponding axis position
Here's the code (08-acceleration-3.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Acceleration 3</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
ball = new Ball(),
vx = 0,
vy = 0,
ax = 0,
ay = 0;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
window.addEventListener('keydown', function (event) {
switch (event.keyCode) {
case 37: //left
ax = -0.1;
break;
case 39: //right
ax = 0.1;
break;
case 38: //up
ay = -0.1;
break;
case 40: //down
ay = 0.1;
break;
}
}, false);
window.addEventListener('keyup', function () {
Search WWH ::




Custom Search