Stwosch
Stwosch

Reputation: 642

Javascript - requestAnimationFrame with WebSockets - performance issues

I have in plan to write a real time "game" for hobby purposes. My idea is to use websockets and canvas and I want to imitate same behaviour as slither.io has, so I would like to have a feature that when user moves, other users can see his move in the same time.

First think that I had in my mind, was to use WebSockets and requestAnimationFrame, so I could for each frame emit event from the client to the server via socket and give information about my coordinates to other sockets.

My problem is that I'm troubling that this will not efficient and would kill my server with the events.

So is it good way to design real time communication in browser game or is there a better way to do this?

Upvotes: 0

Views: 1163

Answers (1)

Ruzihm
Ruzihm

Reputation: 20259

You can certainly use WebSockets, and there are some great resources at the question here: Are WebSockets suitable for real-time multiplayer games?

You should consider a slower tick rate than just doing it once for every animation frame. Making a state update every video frame, which might be happening up to 60 times per second, is probably overkill. Overwatch, which is a moderate-paced game, does one just over every 20 seconds, for comparison.

To do the state update independently, for example in socket.io, you could use setInterval

var dataTickRate = 30;

setInterval(function() {
  socket.emit('playerState', playerState);
}, 1000 / dataTickRate);

Upvotes: 1

Related Questions