Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question
    
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. –  Byte56 Oct 15 '14 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. –  Tommy Otzen Oct 15 '14 at 21:59

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
Worked perfectly! Good explanation too and links. –  Tommy Otzen Oct 16 '14 at 7:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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