Во-первых, вы должны изучить прототип наследования!Таким образом, каждый Player
будет иметь свою собственную копию метода draw
, поэтому вместо Player.prototype
укажите draw
:
var Player = function(context, x, y) {
this.context = context;
this.x = x;
this.y = y;
};
Player.prototype = {
draw: function() {
this.context.fillRect(this.x, this.y, 16, 16);
}
};
Затем я предлагаю добавить move
метод Player
:
Player.prototype = {
draw: function() {
this.context.fillRect(this.x, this.y, 16, 16);
},
move: function(direction) {
// direction is "UP", "DOWN", "LEFT" or "RIGHT"
switch(direction) {
case "UP":
this.y += 16;
break;
// ...
}
}
};
Затем в обработчике сообщений вам просто необходимо:
socket.on('b', function(data) {
players[data.player].move(data.direction);
draw();
});
На сервере вы, например, emit('b', { player: playerId, direction: "UP" }
.
Обновление: Вместо draw
внутри socket.on('b', ...
выше, вы можете иметь что-то вроде:
setInterval(draw, 100);
Перерисовывать каждые 100 мс.Я думаю, это зависит от типа игры.