I have an animation of a bullet but it seems to be going much faster than i was expecting.

I currently set it to 0.5 pixels per second yet it seems to be moving way over hundreads of pixels per second.

Not quite sure where my logic is going wrong:

This is inside my gameLoop which im using to calculate it:

var deltaTime = (new Date().getTime() - started) / 1000; // divide to get seconds    
var position = deltaTime * bulletVelocity; //bulletVelocity is 0.5

var vectorX = destinationX - startX;
var vectorY = destinationY - startY;
var distance = Math.sqrt(vectorX * vectorX + vectorY * vectorY);

var x = startX + (vectorX * position);
var y = startY + (vectorY * position);

if (x < destinationX && y < destinationY) {
    ctx2.drawImage(pulse, x, y); //draw the sprite on canvas

Have i got my logic wrong here i cannot work out why its moving so fast.

  • \$\begingroup\$ You multiply the speed by the total distance to travel. That does not immediately make sense to me. You should comment your own code to explain what it is doing. The problem might become apparent if you try to express it explicitly. \$\endgroup\$ Dec 9 '13 at 1:41
  • 1
    \$\begingroup\$ This question appears to be off-topic because it is about debugging your code for you. \$\endgroup\$ Dec 9 '13 at 1:41
  • \$\begingroup\$ @SethBattin i multiply the timeElapsed which is deltaTime by velocity on line 2? Where am i multiplying distance by speed? \$\endgroup\$
    – Dave
    Dec 9 '13 at 1:43
  • \$\begingroup\$ var position = deltaTime * bulletVelocity; and var vectorX = destinationX - startX; and then var x = startX + (vectorX * position) \$\endgroup\$ Dec 9 '13 at 1:44
  • \$\begingroup\$ @SethBattin so its the last two vars where my logic failed? \$\endgroup\$
    – Dave
    Dec 9 '13 at 1:46

You forgot to divide 'vectorX' and 'vectorY' by 'distance'.

If you do that, the code should work.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.