5

How I can rotate an object in Box2D? Tried..

private static final double DEGREES_TO_RADIANS = (double)(Math.PI/180);
float angle = (float) (45*DEGREES_TO_RADIANS);
object.body.setTransform(object.body.getPosition(), angle);

..but not working.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
lacas
  • 13,928
  • 30
  • 109
  • 183

5 Answers5

2

If you want to rotate the object to an angle then you use setTransform method like

b2body->SetTransform( playerBody_->GetPosition(), angleInRadian );

And if you want to rotate the body continuously then use SetAngularVelocity method like

b2body->SetAngularVelocity(<float32>)

Remember b2body object must be a dynamic or kinematic to be able to be rotated.

Ali Raza
  • 613
  • 5
  • 17
2

Firstly the object must be a dynamic or kinematic to be able to be rotated, in addition use SetAngularVelocity() to achieve the rotation.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

I think you can use force or impulses,not use setTransform methord directly. example:

body->ApplyForce( b2Vec2(force,0), body->GetWorldPoint( b2Vec2(1,1) ) );

this code let body rote.

Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50
Snow
  • 13
  • 5
1

use the world center instead position, like this

private static final double DEGREES_TO_RADIANS = (double)(Math.PI/180);
float angle = (float) (45*DEGREES_TO_RADIANS);
object.body.setTransform(object.body.getWorldCenter(), angle);
Matrix Bai
  • 1,097
  • 3
  • 11
  • 20
-1

The idea is to rotate to an angle, the easiest method I found by myself is to use:

float rotation = MathUtils.PI; // target rotation

float c = 1; //speed of rotation
float q = rotation-groundBody.getAngle();
groundBody.setAngularVelocity(c*q);

the body will rotate quicker at the beginning and slower at the end but you can use Interpolation function to achieve desired speed of rotation.

LionH
  • 194
  • 6