Box2d Apply force in a certain direction

I want to apply force to my object in the direction that it is now, here is my code so far, but it throws errors when I try to do force * t , what am I doing wrong?

  b2Transform t; t.Set(b2Vec2(0, 0), spaceCraft->GetAngle()); b2Vec2 force = b2Vec2(0, 2.5f); spaceCraft->ApplyForce(force * t, spaceCraft->GetPosition()); 
+4
source share
3 answers

The easiest way is to look at the direction the object β€œcollides” when you define the body, and use GetWorldVector to see how it changes. For example, if it is facing straight up, when you create a body, this will be the direction (0,1). Then you can use GetWorldVector at any time to get the current direction of this vector in world coordinates to apply force:

 b2Vec2 forceDirection = body->GetWorldVector( b2Vec2(0,1) ); 
+3
source

I can't try it right now, but something like that:

 float magnitude=2.5f; b2Vec2 force = b2Vec2(cos(spaceCraft->GetAngle()) * magnitude , sin(spaceCraft->GetAngle()) * magnitude); spaceCraft->ApplyForce(force, spaceCraft->GetPosition()); 
+8
source

You can try as suggested by IFORCE2D

 float mangnitude = anything; b2Vec2 forceDirection = body->GetWorldVector( b2Vec2(0,1) ); forceDirection = magnitude * forceDirection; body->ApplyLinearImpulse(forceDirection, body->GetPosition(), true); 
0
source

Source: https://habr.com/ru/post/1400112/


All Articles