HTML5 Canvas、JavaScript(John Resig simple Inheritanceライブラリを使用しすぎます)、およびSocket.IOを使用したNode.jsを使用して、シンプルなマルチプレーヤーを作成しようとしています。私のクライアントコード:
var canvas = document.getElementById( 'game');
var context = canvas.getContext( '2d');
var socket = new io.Socket( '127.0.0.1'、{port:8080});
var player = null;
var UP = 'UP'、
LEFT = 'LEFT'、
DOWN = 'DOWN'、
RIGHT = 'RIGHT';
socket.connect();
socket.on( 'connect'、function(){socket.send();
console.log( 'Connected!');
player = new Player(50、50);
});
socket.on( 'message'、function(msg){
if(msg == 'UP'){
player.moveUP();
} else if(msg == 'LEFT'){
player.moveLEFT();
} else if(msg == 'DOWN'){
player.moveDOWN();
} else if(msg == 'RIGHT'){
player.moveRIGHT();
} そうしないと {
}
});
socket.on( 'disconnect'、function(){
console.log( 'Disconnected!');
});
var Player = Class.extend({
init:function(x、y){
this.x = x;
this.y = y;
}、
setX:function(x){
this.x = x;
}、
getX:function(){
this.xを返します。
}、
setY:function(y){
this.y = y;
}、
getY:function(){
this.yを返します。
}、
draw:function(){
context.clearRect(0、0、350、150);
context.fillRect(this.x、this.y、15、15);
}、
move:function(){
this.x + = 1;
this.y + = 1;
}、
moveUP:function(){
this.y--;
}、
moveLEFT:function(){
this.x--;
}、
moveDOWN:function(){
this.y ++;
}、
moveRIGHT:function(){
this.x ++;
}
});
関数checkKeyCode(event){
var keyCode;
if(event == null){
keyCode = window.event.keyCode;
} そうしないと {
keyCode = event.keyCode;
}
switch(keyCode){
ケース38:// UP
player.moveUP();
socket.send(UP);
ブレーク;
ケース37://左
player.moveLEFT();
socket.send(LEFT);
ブレーク;
ケース40:// DOWN
player.moveDOWN();
socket.send(DOWN);
ブレーク;
ケース39://右
player.moveRIGHT();
socket.send(RIGHT);
ブレーク;
デフォルト:
ブレーク;
}
}
関数update(){
player.draw();
}
var FPS = 30;
setInterval(function(){
更新();
player.draw();
}、1000 / FPS);
関数init(){
document.onkeydown = checkKeyCode;
}
初期化();
サーバーコード:
var http = require( 'http')、
io = require( 'socket.io')、
buffer = new Array()、
server = http.createServer(function(req、res){
res.writeHead(200、{'Content-Type': 'text / html'});
res.end( 'こんにちは世界
');
});
server.listen(8080);
var socket = io.listen(server);
socket.on( 'connection'、function(client){
client.on( 'message'、function(message){
console.log(message);
client.broadcast(message);
})
client.on( 'disconnect'、function(){
})
});
2つのクライアントを実行すると、最初のクライアントで2番目のクライアントRectを移動でき、2番目のクライアントで最初のクライアントrectを移動できます。
本物のマルチプレイヤーを作成する方法について質問がありますか?3つのクライアントを開き、最初のクライアントがrect1、2番目のrect2、最後のrect3を取得します。最初のクライアントはrect1のみを移動でき、3番目のクライアントはrect3のみを移動できます。
たぶん誰もが考えていますか?Googleで検索しましたが、答えが見つかりません。
英語をありがとう、ありがとう。