I am developing a multiplayer game in PHP using Canvas and MySQL database.
Two players join the game and they first get opponent’s position(X,Y and Angle).
When they’re ready, game starts. Game Algorthim goes like this.
Every 50 millisec
- Calculate their own position (X,Y)
- Get opponent’s angle(AJAX) and calculate opponents pos (X2, Y2)
-
Then draw on Canvas and update database.
context.fillStyle = "green"; context.fillRect(p1.x,p1.y, 5,5); addPoints(p1.x,p1.y); updateRoundJQ(p1.x,p1.y,p1.a); context.fillStyle = "red"; context.fillRect(x2,y2, 5,5); addPoints(x2,y2); loopTimer = setTimeout('drawLine()', 50);
But unfortunately I get this result. There’s a great delay in receiving the data. Could anyone please help me how to get rid of this great error? It would be really thankful.
Player 1’s screen

Player 2’s screen

Your script isn’t running every 50ms – as it is only setting the timeout once all the other functions have run. Depending on how
updateRoundworks, this could add the time of a round trip to each interval.For example, consider the following timings:
So, with these example timings, your loop will only run after ~306ms.
It may be worth considering pushing the data to your client using websockets, rather than pulling it with AJAX.