Please solve this confusion 🤔. Why we use time speed*timePassed. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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); }

6th Sep 2022, 4:16 AM
Raja Rawat
Raja Rawat - avatar
3 Answers
+ 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.
6th Sep 2022, 4:31 AM
Daniel C
Daniel C - avatar
6th Sep 2022, 6:24 AM
Raja Rawat
Raja Rawat - avatar
6th Sep 2022, 4:44 AM
Prashanth Kumar
Prashanth Kumar - avatar