# Get speed from vector using box2d and javascript

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:

 GetLinearVelocity().x;
GetLinearVelocity().y;


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);
console.log(speed);


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.

• 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. Oct 15, 2014 at 20:16
• It seems that the input for from GetLinearVelocity () has negative values therefor Math.sqrt gives NaN output. I'll try the solution below. Oct 15, 2014 at 21:59

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.

• Worked perfectly! Good explanation too and links. 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);