Multiplayer with Web Sockets

Still haven’t had much to blog about lately, so this may be a short post. I didn’t even make a post last month, but there were a couple interesting new techniques I’ve been mastering since my last post. One is using the stencil buffer in custom shaders, and the other is using web sockets to implement multiplayer.

If you are new to the concept, the stencil buffer is simply another array of pixels you can draw to, just like the color and depth buffers. As the name implies, it’s useful for drawing stencil masks. As in, you can draw a shape on the stencil buffer, and then have that shape cut out of subsequent render passes.

I found this to be really useful for rendering UI elements in the scene. In my case, I wanted lines drawn on top of the ground that appeared under other objects. What I did was simply draw the silhouette of objects into the stencil buffer while rendering those objects. Then I drew the lines last, on top of everything, but cutting out the silhouettes in the stencil buffer. Perfect!

As for multiplayer using web sockets, there’s not a ton for me to explain, other than that it was super fun to implement. The server is written in Node.js (here’s one simple explanation of how) while the Unity client simply uses a C# web sockets library. I’ve been using this library, but as that link says it’s been deprecated, so I might switch to this library, or even drop some money on this very highly rated asset.

Then I simply send JSON strings back and forth over the sockets. The messages are as simple as a “type” field so the receiver (client or server) can tell what to do with a given message, and then a “payload” field with the data they respond to.

I gotta say, building this has been very interesting. Right now as I type this, I’m suddenly having an idea where a community of players are all interacting live in a mostly text-based game. hm I just described a MUD didn’t I? I wonder if an ad-supported MUD would do well on mobile…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s