Creating a canvas ball seamlessly

I wrote a multiplayer pong game, but due to a 60 ms lag my jumping ball does not move smoothly. The game itself is available here , but since it only works in chrome, and the site itself is written in my native language (you also obviously need two browsers to make it work), here's the jsfiddle problem:

http://jsfiddle.net/yc6Lb/75/

As you can see in the script, dx and dy defined, and the update per second is defined as speed . I need these three variables to remain constant (I know that they cause the ball to not move smoothly).

Now the question is: are there any tricks not to touch these variables, but to make the ball look like it is moving smoothly? I was thinking about rendering a new ball position + rendering a previous ball position with an opacity of 50%, but I still have to check it. Are there any other solutions to this problem?

+6
source share
4 answers

I think, as Jason said, that you can make such a step as accurate as you want in animation (for example, using animation), and separately handle the problem of receiving remote information. However, for a quick fix, you can use the trick I sometimes use: to have a trace / shadow effect, clearing the 2D context with reduced opacity.
Thus, a clear function becomes:

 function clear() { cxt.globalAlpha=0.3; cxt.fillStyle='#FFFFFF'; cxt.fillRect(0, 0, WIDTH, HEIGHT); cxt.globalAlpha=1; } 

then you should not clear the draw () function and call clear () on the paint path.

I updated your fiddle:

http://jsfiddle.net/gamealchemist/yc6Lb/86/

play with alpha to get the desired effect.

Rq: you can clear some parts of the screen (for example, grading) with full opacity and use less opacity only in the animated part of the canvas.

+3
source

This is ugly, but here is the FPS link for you: http://jsfiddle.net/yc6Lb/84/

In particular, using requestAnimationFrame() and having an FPS counter. Pay attention to the difference in performance :)

Here's BEAUTIFUL CODE : http://jsfiddle.net/neuroflux/Ey9uz/1/
Welcome!

+3
source

You can get a little performance without doing your 2 * pi calc in each loop. Turn it to a static value of 6.28.

You can also see processing.js , which can speed up the process.

0
source

There is nothing wrong with your math. You must use requestAnimationFrame. Change your init function to look like this:

 function init() { window.requestAnimationFrame(init, cxt) draw(); } 

Here is a working JSFiddle example

You will also need a polyfill for requestAnimationFrame to make it work in all browsers.

-1
source

Source: https://habr.com/ru/post/956588/


All Articles