I need to find the speed of an object in a game. The game is made in HTML5 with jquery and jquery.box2d. For this I can use these methods:


I'm then trying to calculate the speed from this piece of code, but get some values that doesn't make sense when I console.log it. This is my code:

 var heroVelX = game.currentHero.GetLinearVelocity().x;
 var heroVelY = game.currentHero.GetLinearVelocity().y;

 var speed = Math.sqrt(heroVelX^2 + heroVelY^2);

Some of the values in console.log are numbers, but most of them are NaN (Not-A-Number), which confuses me? Can someone help me solve this?

The goal I want to achieve, is to see when the speed(of object .currenHero) drop below a certain value, so I can excute a new state in the game.

  • \$\begingroup\$ You'd have to find out what the values are going into the equation to find out why you're getting NaN as a result. Speed is the magnitude of the velocity vector, so it appears you're doing things correctly (if you're using the correct syntax). Likely something is wrong before you perform this calculation. Basic debugging steps like outputting your velocity x and y values will help you track down what's going wrong. \$\endgroup\$
    – House
    Oct 15, 2014 at 20:16
  • \$\begingroup\$ It seems that the input for from GetLinearVelocity () has negative values therefor Math.sqrt gives NaN output. I'll try the solution below. \$\endgroup\$ Oct 15, 2014 at 21:59

2 Answers 2


Try this:

var speed = Math.sqrt(Math.pow(heroVelX, 2) + Math.pow(heroVelY, 2));

The case is that the ^ operator is the bitwise XOR operator. You should use Math.pow(base, exponent).

Here is a an example: link.

  • \$\begingroup\$ Worked perfectly! Good explanation too and links. \$\endgroup\$ Oct 16, 2014 at 7:02

You could use Math.hypot() for the magnitude of a right-angled triangle:

const speed = Math.hypot(heroVelX, heroVelY);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .