HTML:
<canvas id="world" style="height: 300px; width: 300px;" />
JS:
console.log("Game starting...");
var ship = new Object();
ship.name = "Enterprise";
ship.x = 0;
ship.y = 0;
ship.width = 50;
ship.left = false;
ship.right = false;
ship.up = false;
ship.down = false;
ship.fire = false;
ship.firerate = 5;
ship.cfirerate = 0;
var lazers = new Array();
var world = document.getElementById('world');
var cxt = world.getContext("2d");
$(document).bind('keydown', function(e) {
if(e.keyCode==37){
ship.left = true;
}
if(e.keyCode==38){
ship.up = true;
}
if(e.keyCode==39){
ship.right = true;
}
if(e.keyCode==40){
ship.down = true;
}
if(e.keyCode==90){ //Z
console.log("pew pew");
ship.fire = true;
}
});
$(document).bind('keyup', function(e) {
if(e.keyCode==37){
ship.left = false;
}
if(e.keyCode==38){
ship.up = false;
}
if(e.keyCode==39){
ship.right = false;
}
if(e.keyCode==40){
ship.down = false;
}
if(e.keyCode==90){ //Z
ship.fire = false;
}
});
function createLazer(type) {
if (type == 1) {//LEFT LAZER
cxt.beginPath();
cxt.moveTo(125+ship.x,140+ship.y);
cxt.lineTo(125+ship.x,130+ship.y);
var l = new Object();
l.type = type;
l.x = ship.x;
l.y = ship.y;
return l;
}
else if (type == 2) {//RIGHT LAZER
cxt.beginPath();
cxt.moveTo(125+ship.x+ship.width,140+ship.y);
cxt.lineTo(125+ship.x+ship.width,130+ship.y);
var l = new Object();
l.type = type;
l.x = ship.x;
l.y = ship.y;
return l;
}
}
function drawWorld() {
cxt.fillStyle="#808080";
cxt.fillRect(0,0,300,300);
}
function drawLazers() {
for (x = 0; x < lazers.length; x++)
{
cxt.beginPath();
cxt.strokeStyle="#FF0000";
if (lazers[x].type == 1) {
cxt.moveTo(125+lazers[x].x,140+lazers[x].y);
cxt.lineTo(125+lazers[x].x,120+lazers[x].y);
}
else if (lazers[x].type == 2) {
cxt.moveTo(125+lazers[x].x+ship.width,140+lazers[x].y);
cxt.lineTo(125+lazers[x].x+ship.width,120+lazers[x].y);
}
cxt.stroke();
lazers[x].y = lazers[x].y - 6;
//console.log("drawing lazer" + lazers[x].x + lazers[x].y);
}
}
function drawShip() {
if (ship.left) { ship.x = ship.x -5; }
if (ship.right) { ship.x = ship.x +5; }
if (ship.up) { ship.y = ship.y -5; }
if (ship.down) { ship.y = ship.y +5; }
if (ship.fire) {
if (ship.cfirerate == 0) {
lazers.push(createLazer(1));
lazers.push(createLazer(2));
ship.cfirerate = ship.firerate;
}
}
if (ship.cfirerate != 0) {
ship.cfirerate = ship.cfirerate - 1;
}
cxt.beginPath();
cxt.strokeStyle="#000000";
cxt.moveTo(125+ship.x,140+ship.y);
cxt.lineTo(150+ship.x,120+ship.y);
cxt.lineTo(175+ship.x,140+ship.y);
cxt.stroke();
}
function clear() {
cxt.clearRect(0, 0, 300, 300);
}
function gameLoop() {
drawWorld();
drawShip();
drawLazers();
}
setInterval(function() {
clear();
gameLoop();
}, 30);