+ 1
Please solve this confusion 🤔. Why we use time speed*timePassed.
We can use this if(dir == 1) { x += 5; } else if(dir == 2) { x -= 5; } But why this⬇️ function draw() { var timePassed = (Date.now() - t) / 1000; t = Date.now(); var fps = Math.round(1 / timePassed); context.clearRect(0, 0, 600, 400); context.beginPath(); context.rect(x, y, 100, 100); context.fillStyle="red"; context.fill(); if(dir == 1) { x += (speed * timePassed); } else if(dir == 2) { x -= (speed * timePassed); }
3 odpowiedzi
+ 5
In your case, using the number "5" is what's called a "magic number" in programming. What this means is that, to anybody looking at the code, it's just an arbitrary fixed number that hasn't even been assigned to a variable.
However, using speed * timePassed means you'll keep a consistent movement regardless of the framerate, since timePassed is calculating how much time has elapsed since the last frame. As a result, both low and high framerates will see the x value changing by the same amount.
If 5 was used instead, a lower framerate would see x moving a lot slower than a higher framerate.
+ 3
Thanks Daniel C and Prashanth Kumar
+ 2
have a look at this .
- https://youtu.be/8pYq15Lh0x4
- https://youtu.be/XuyrHE6GIsc