HTML and CSS Reference
In-Depth Information
document.onkeydown = function(e){
e=e?e:window.event;
//ConsoleLog.log(e.keyCode + "down");
keyPressList[e.keyCode] = true;
}
document.onkeyup = function(e){
//document.body.onkeyup=function(e){
e = e?e:window.event;
//ConsoleLog.log(e.keyCode + "up");
keyPressList[e.keyCode] = false;
};
Evaluating key presses
Our game will need to include code to look for true (or false ) values in the keyPress
List array, and use those values to apply game logic:
if (keyPressList[38]==true){
//thrust
var angleInRadians = player.rotation * Math.PI / 180;
facingX = Math.cos(angleInRadians);
facingY = Math.sin(angleInRadians);
movingX = movingX+thurstAcceleration*facingX;
movingY = movingY+thurstAcceleration*facingY;
}
if (keyPressList[37]==true) {
//rotate counterclockwise
rotation-=rotationalVelocity;
}
if (keyPressList[39]==true) {
//rotate clockwise
rotation+=rotationalVelocity;;
}
Let's add this code to our current set of rotation examples and test it out. We have
made some major changes, so Example 8-8 presents the entire HTML file once again.
Example 8-8. Controlling the player ship
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH8EX8: Ship Turn With Keys</title>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
Search WWH ::




Custom Search