Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use a simple interpolation formula where you animate it by adjusting the factor <code>f</code>.</p> <p>The formula is (shown only for <code>x</code>):</p> <pre><code>x = x1 + (x2 - x1) * f </code></pre> <p>An example on how to implement -</p> <p><strong><a href="http://jsfiddle.net/AbdiasSoftware/e42k7/" rel="nofollow">AN ONLINE DEMO</a></strong></p> <pre><code>/// add click callback for canvas (id = demo) demo.onclick = function(e) { /// get mouse coordinate var rect = demo.getBoundingClientRect(), /// gun at center bottom x1 = demo.width * 0.5, y1 = demo.height, /// target is where we click on canvas x2 = e.clientX - rect.left, y2 = e.clientY - rect.top, /// factor [0, 1] is where we are at the line f = 0, /// our bullet x, y; loop(); } </code></pre> <p>Then we provide the following code for the loop</p> <pre><code>function loop() { /// clear previous bullet (for demo) ctx.clearRect(x - 2, y - 2, 6, 6); /// HERE we calculate the position on the line x = x1 + (x2 - x1) * f; y = y1 + (y2 - y1) * f; /// draw some bullet ctx.fillRect(x, y, 3, 3); /// increment f until it's 1 if (f &lt; 1) { f += 0.05; requestAnimationFrame(loop); } else { ctx.clearRect(x - 2, y - 2, 6, 6); } } </code></pre> <p>To draw a "longer" bullet that follows the line you can either store an older value of the x/y pair and draw a line between that and current, or less optimal, calculate the position separately or even calculate the angle and use a fixed length.</p> <p>Also worth to be aware of: the longer the line is the faster the bullet goes. You can calculate a delta value for <code>f</code> based on length (not shown in demo) to get around this.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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