简单的多人游戏系统开发
还是向 tsoding 学习,看他视频可以学到很多,例如一开始使用 json 传递数据,后面为了优化性能,需要去做一些统计,发现性能关键问题,做去思考优化。
后端这边我用 Go 去写。
玩家移动
当玩家移动时,需要计算新的位置,server 这边收到需要移动的消息,会在下一帧中同步移动消息到所有 player,并在 server 中计算新的位置,则 client 收到消息则更新 player 的 state 为 server 最新的发送的,并在下一帧中更新计算新的位置。这样两边同步计算,不需要依赖 server 端的计算,尽可能的尽快渲染。因为网络通信都有会延迟。
通过 mask,可以记录短时间内多次移动情况。
Websocket
“text frames” – contain text data that parties send to each other.
“binary data frames” – contain binary data that parties send to each other.
“ping/pong frames” are used to check the connection, sent from the server, the browser responds to these automatically.
there’s also “connection close frame” and a few other service frames.
In the browser, we directly work only with text or binary frames.
在 js 这边可以处理的 binaryMessage 两种格式,一种默认使用的是 Blob,一种是 ArrayBuffer
A call socket.send(body) allows body in string or a binary format, including Blob, ArrayBuffer, etc. No settings are required: just send it out in any format.
When we receive the data, text always comes as string. And for binary data, we can choose between Blob and ArrayBuffer formats.
That’s set by socket.binaryType property, it’s "blob" by default, so binary data comes as Blob objects.
Blob is a high-level binary object, it directly integrates with and other tags, so that’s a sane default. But for binary processing, to access individual data bytes, we can change it to "arraybuffer":