add start of ship controls

This commit is contained in:
Asraelite 2016-03-22 00:42:48 +00:00
parent 1027d980c1
commit fcfe1e8790
10 changed files with 131 additions and 2 deletions

View file

@ -0,0 +1,62 @@
function Input() {
this.mouse = {
x: 0,
y: 0,
held: {},
pressed: {}
};
this.keys = {
held: {},
pressed: {}
};
this.mouseMove = function (el) {
return function (event) {
var rect = game.renderer.canvas.getBoundingClientRect();
el.mouse.x = event.clientX - rect.left;
el.mouse.y = event.clientY - rect.top;
}
};
this.mouseDown = function (el) {
return function (event) {
el.mouse.pressed[event.which] = true;
el.mouse.held[event.which] = true;
}
};
this.mouseUp = function (el) {
return function (event) {
el.mouse.held[event.which] = false;
}
}
this.keyDown = function (el) {
return function (event) {
if (!el.keys.held[event.which]) el.keys.pressed[event.which] = true;
el.keys.held[event.which] = true;
}
}
this.keyUp = function (el) {
return function (event) {
el.keys.held[event.which] = false;
}
}
document.addEventListener('mousemove', this.mouseMove(this));
document.addEventListener('mousedown', this.mouseDown(this));
document.addEventListener('mouseup', this.mouseUp(this));
document.addEventListener('keydown', this.keyDown(this));
document.addEventListener('keyup', this.keyUp(this));
this.mouseAnyPressed = function () {
var p = this.mouse.pressed;
return p[1] || p[2] || p[3];
}
this.clear = function () {
for (var i in this.keys.pressed) this.keys.pressed[i] = false;
for (var i in this.mouse.pressed) this.mouse.pressed[i] = false;
};
}

View file

@ -18,6 +18,7 @@ function Game() {
this.connected = false;
this.state = 'connecting';
this.input = new Input();
this.net = new Net();
this.world = new World();
this.renderer = new Renderer();
@ -25,6 +26,17 @@ function Game() {
this.tick = function() {
self.renderer.render(self.state);
var ship = self.world ? self.world.playerShip : false;
if(ship) {
ship.move[0] = self.input.keys.held[87] || false;
ship.move[1] = self.input.keys.held[65] || false;
ship.move[2] = self.input.keys.held[68] || false;
ship.updateMove();
}
self.input.clear();
requestAnimationFrame(self.tick);
}
}

View file

@ -18,4 +18,12 @@ function Net() {
game.world.update(data);
});
};
this.update = function(move) {
this.socket.emit('move', {
forward: move[0],
left: move[1],
right: move[2]
});
}
}

View file

@ -5,6 +5,8 @@ function Renderer() {
var context = canvas.getContext('2d');
var pallet = new Pallet();
this.canvas = canvas;
this.render = function(state) {
if (state == 'connecting' || state == 'disconnected') {
pallet.clear();

View file

@ -2,4 +2,13 @@ function Ship(id) {
this.id = id;
this.x = 0;
this.y = 0;
this.move = [];
this.lastMove = [];
this.updateMove = function() {
if (JSON.stringify(this.move) != JSON.stringify(this.lastMove) || true) {
game.net.update(this.move);
this.lastMove = Array.apply(0, this.move); // Bloody Javascript.
}
}
}