Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can improve your code in two ways:</p> <ol> <li>Using an absolute tracking instead of relative tracking</li> <li>Using an absolute time control</li> </ol> <h2>Absolute tracking</h2> <p>Javascript uses doubles for all computations so you do not have a real accuracy problem, but the formulas for absolute tracking are more accurate AND easier: given <code>(x0, y0)</code> as starting point and <code>(x1, y1)</code> as ending point you can compute any point inbetween the two with:</p> <pre><code>x = x0 + t*(x1 - x0); y = y0 + t*(y1 - y0); </code></pre> <p>where <code>t</code> goes from 0.0 (start) to 1.0 (end).</p> <h2>Absolute time control</h2> <p>This is where your code has a serious problem. In Javascript (and in most other cases) when you set a timer you cannot be sure that the function will be called <strong>exactly</strong> what you want. The only thing you know for sure is the your function will not be called <strong>more</strong> than what you requested, but it's very common that some calls will be "late" in respect to the period you require. To get a controlled movement over time you need to check the clock instead of just assuming the call time the expected one: to sum up...</p> <pre><code>function animate(div, x0, y0, x1, y1, speed) { var dx = x1 - x0; var dy = y1 - y0; var dist = Math.sqrt(dx*dx + dy*dy); var total_time = dist / speed; var start_time = new Date().getTime(); var cback = setInterval(function() { var now = new Date().getTime(); if (now &gt;= start_time + total_time) { // Animation is complete div.style.left = x1 + "px"; div.style.top = y1 + "px"; //clearInterval(cback); } else { // We are still moving var t = (now - start_time) / total_time; div.style.left = (x0 + t*dx) + "px"; div.style.top = (y0 + t*dy) + "px"; } }, 10); } </code></pre> <p>Also the use of absolute timing simplifies for example "easing" (slow start and stop with acceleration and deceleration): just add after the computation of <code>t</code> the line</p> <pre><code>t = t*t*(3 - 2*t); </code></pre> <p>in this case the <code>speed</code> parameter means the <strong>average</strong> speed in px/ms.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload