【发布时间】:2022-01-05 22:44:58
【问题描述】:
我一直在阅读很多关于不同的人如何在他们的多人游戏中实现 socket.io,以便我可以在我的游戏中使用它。诚然,我是网络层的菜鸟,我迫切需要学习。
代码上下文:
-使用 Phaser3
-多人游戏
-加载所有现有玩家
-播放器加入
-更新玩家位置
问题:
-似乎只更新加入并广播它的最新套接字的位置
-可能不重要,但传入的 socket.id 似乎替换了它设置为 id 的最后一个 socket.id,我认为这是因为“如果传入的套接字不等于你的套接字则运行”的参数确实不运行
-一般来说,不更新游戏中其他玩家的状态(不移动其他玩家)
server.js:
const http = require('http');
const cors = require('cors');
const express = require('express');
const app = express();
const server = http.createServer(app);
const io = require('socket.io')(server,{cors:{origin:'http://localhost:8080',methods:['POST','GET']}});
const universe = {0:{},1:{},2:{},3:{},4:{},5:{},6:{},7:{},8:{},9:{}}
io.on('connection',(socket)=>
{
console.log(`${socket.id} joined the universe!`);
universe['0'][socket.id] = {playerID:socket.id};
console.log(`Online players: ${JSON.stringify(universe['0'])}`)
io.emit('join',socket.id, null); //sending to all clients and client
socket.emit('loadUniverse', universe['0']); //sending to client only
socket.on('updatePos',(player,vx,vy)=>
{
socket.broadcast.emit("updatePos1", player,vx,vy);
})
socket.on('disconnect',()=>
{
delete universe['0'][socket.id]
//emit a delete event
console.log(`${socket.id}player left the universe!`)
})
})
server.listen(3000,()=>{console.log('listening on port 3000')})
相关客户:
scene.socket.on('connect',()=> //needs to chain from the connect
{
this.scene.socket.emit('join',this.socketID)
console.log(`connected`);
})
scene.socket.on('updatePos1',(socketID1,vx,vy)=>
{ //this is a callback
console.log(`Message Recieved: ${socketID1}: ${vx} ${vy}`)
console.log(`players: ${JSON.stringify(this.scene.gameHandler.players)}`)
if(this.socketID!==socketID1)
{
console.log('socket was not yours!');
this.scene.gameHandler.players[socketID1].sprite.body.setVelocity(vx,vy);
}
})
scene.socket.on('join',(socketID0,skin)=>
{
console.log(`Player ${socketID0} joined`);
this.socketID = socketID0;
this.scene.gameHandler.loadPlayer(socketID0,skin);
})
scene.socket.on('loadUniverse',(universe)=>
{
for(const property in universe)
{
console.log(`propery:${property}`);
this.scene.gameHandler.loadPlayer(property,null);//make this dynamic
}
})
updatePos()
{
console.log(`${this.socketID} for updatePos()`)
this.scene.socket.emit(
'updatePos',this.socketID, //might have to do with how broadcasted
this.scene.gameHandler.players[this.socketID].sprite.body.velocity.x, //not updating individual position
this.scene.gameHandler.players[this.socketID].sprite.body.velocity.y,
)
}
在 game.js update() 函数(phaser3 库的标准事件循环)中,我正在使用上面的“updatePos()”函数更新客户端位置。
问题:
我做错了什么?为什么会出错?
【问题讨论】:
标签: javascript node.js networking websocket socket.io