1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\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\$ – MichaelHouse Oct 15 '14 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\$ – Tommy Otzen Oct 15 '14 at 21:59
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Worked perfectly! Good explanation too and links. \$\endgroup\$ – Tommy Otzen Oct 16 '14 at 7:02

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.