HTML and CSS Reference
In-Depth Information
Thrusting in the rotated direction
Once the ship is rotated to the desired direction, the player can thrust it forward by
pressing the up arrow key. This thrust will accelerate the player ship only while the key
is pressed. Since we know the rotation of the ship, we can easily calculate the angle of
the rotation. We will then add new movingX and movingY values to the ship's x and y
attributes to move it forward.
First, we must change the rotation value from degrees to radians:
var angleInRadians = rotation * Math.PI / 180;
You have seen this beforeā€”it's identical to how we calculated the rotation transfor-
mation before it was applied to the player ship.
Once we have the angle of the ship's rotation, we must calculate the facingX and
facingY values for this current direction. We only do this when we are going to thrust
because it is an expensive calculation, processor-wise. We could calculate these each
time the player changes the ship's rotation, but doing so would add unnecessary pro-
cessor overhead:
facingX = Math.cos(angleInRadians);
facingY = Math.sin(angleInRadians);
Once we have values on the x and y axes that represent the direction the player ship is
currently facing, we can calculate the new movingX and movingY values for the player:
movingX = movingX+thrustAcceleration*facingX;
movingY = movingY+thrustAcceleration*facingY;
To apply these new values to the player ship's current position, we need to add them
to its current x and y positions. This does not occur only when the player presses the up
key . If it did, the player ship would not float; it would only move when the key was
pressed. We must modify the x and y values on each frame with the movingX and
movingY values:
x = x+movingX;
y = y+movingY;
Redrawing the player ship to start at angle 0
As you may recall, when we first drew the image for our player ship, we had the point
end (the top) of the ship pointing up. We did this for ease of drawing, but it's not really
the best direction in which to draw our ship when we intend to apply calculations for
rotational thrust. The pointing-up direction is actually the -90 (or 270 ) degree angle. If
we want to leave everything the way it currently is, we will need to modify the angleIn
Radians calculation to look like this:
var angleInRadians = (Math.PI * (player.rotation -90 ))/ 180;
Search WWH ::

Custom Search