Calculate speed from velocity vector using box2d GetLinearVelocity();

946 Views Asked by At

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.

2

There are 2 best solutions below

5
ydaniv On BEST ANSWER

Your problem is that you're using the wrong operator (Bitwise XOR) for doing square - see here.

What you need to do is:

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

The only time the square root function should return NaN is when the value being square rooted is negative. A way to go about testing if this is the issue would be to try squaring the values in a different line of code before square rooting them.

heroVelX = (heroVelX) * (heroVelX)

Another way to potentially shine some light on the problem would be to add log statements printing out the values of the velocities and the velocities squared before square rooting.