HTML and CSS Reference
In-Depth Information
thrust = 0;
ship.x = canvas.width / 2;
ship.y = canvas.height / 2;
window.addEventListener('keydown', function (event) {
switch (event.keyCode) {
case 37: //left
vr = -3;
break;
case 39: //right
vr = 3;
break;
case 38: //up
thrust = 0.05;
ship.showFlame = true;
break;
}
}, false);
window.addEventListener('keyup', function () {
vr = 0;
thrust = 0;
ship.showFlame = false;
}, false);
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ship.rotation += vr * Math.PI / 180;
var angle = ship.rotation, //in radians
ax = Math.cos(angle) * thrust,
ay = Math.sin(angle) * thrust;
vx += ax;
vy += ay;
ship.x += vx;
ship.y += vy;
ship.draw(context);
}());
};
</script>
</body>
</html>
First you define vr , rotational velocity, or how fast the ship is going to turn when you tell it to turn. It's set to
zero to start, which means the ship won't turn at all:
var vr = 0;
But in the keydown event listener, if the switch statement finds that the left or right cursor keys are
pressed, it sets vr to -3 or 3, respectively:
Search WWH ::




Custom Search