HTML and CSS Reference
In-Depth Information
case 37: //left
vr = -3;
break;
case 39: //right
vr = 3;
break;
Then, in the drawFrame function, you add vr to the ship's current rotation, turning the ship one way or the
other. When a key is released, reset vr to zero. That takes care of rotation, now let's look at thrust.
You have your spaceship there, and you aimed it where you want it to go—3, 2, 1, blastoff! So, how do
you get this thing to go somewhere? Well, it's pretty much just the opposite of what you just did in the
revised mouse follower example. In that example, you calculate an angle and then figure out rotation and
acceleration based on that. Here, you start with the rotation and work backward to find the angle and then
the force on x and y
Declare a thrust variable to keep track of how much force is applied at any given time. Obviously,
acceleration is going to happen only if the rocket is fired, so this starts out as zero:
var thrust = 0;
Then the switch statement comes back into play. If the up cursor key is held down, set thrust to a small
value, say 0.05. This is also where you want to visually indicate that some thrust is applied, by drawing the
flame on the ship:
case 38: //up
thrust = 0.05;
ship.showFlame = true;
break;
Again, when a key is released, set thrust back to zero, and kill the flame.
window.addEventListener('keyup', function () {
vr = 0;
thrust = 0;
ship.showFlame = false;
}, false);
Now, when you get down to the drawFrame function, you know the rotation and you know the force being
applied, if any. Convert rotation to radians and use sine and cosine, along with the thrust variable, to find
the acceleration on each axis:
(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;
Search WWH ::




Custom Search