2
\$\begingroup\$

I need to apply an impulse on a object with a particular force and at a particular angle in Box2d. If I am right the syntax would be the following:

body.GetBody().ApplyImpulse(new b2Vec2(direction, power),body.GetBody().GetWorldCenter());

The problem is my direction is in angles. I found a discussion where it was said that the way we can convert an angle into a vector would be as:

new b2Vec2(Math.cos(angle*Math.PI/180),Math.sin(angle*Math.PI/180));

Now I am not sure how to combine these two. In other words, if I wish to apply a force of 30 units at an angle of 30 degrees at the center of the object, how should I do it?

\$\endgroup\$
3
\$\begingroup\$

The first parameter of applyImpulse is a vector, the direction of the vector indicate the direction the impulse is to be applied and the length of the vector indicates the strength of the impulse.

your code;

new b2Vec2(Math.cos(30*Math.PI/180),Math.sin(30*Math.PI/180));

creates a vector at 30 degrees from the positive x-asis with a length of one. In order to make the vector longer, say 50 units in length(therefore 50 times stronger), just multiply both the x & y components of the vector by 50;

new b2Vec2(50*Math.cos(angle*Math.PI/180),50*Math.sin(angle*Math.PI/180));

similarity of you want a much weaker impulse, you can multiply by a fraction.

More readably, you could write;

 impulse = new b2Vec2(Math.cos(angle*Math.PI/180),Math.sin(angle*Math.PI/180));
 impulse=50*impulse;
 body.GetBody().ApplyImpulse(impulse,body.GetBody().GetWorldCenter());

finally you can use b2Rot() to calculate a vector from an angle;

impuse=new b2Rot(angle).GetXAxis(); // returns a vector at angle degrees to the x-axis
\$\endgroup\$

You must log in to answer this question.

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