b2Body::GetAngle() returning bad data

Hi I'm currently using Box2D version 2.01 for my game engine. I recently changed the way my players move in a realtime isometric simulation. They used to have fixed rotation and animate their rotation based on velocity alone. Now to move to a destination they use an "action" which involves invoking 3 other actions as needed. "FaceDestination" simply calls SetAngle() to face the destination. "Accellerate" makes them accelerate in the direction they are facing. "Brake" attempts to counteract existing velocity.

I noticed my players would start to move in weird semi circles trying to get to their destination. After a lot of debugging efforts I added code to render short lines displaying the result of GetAngle() in red during my render function, a green line for the result of GetAngle() in my logic function, and a blue line from the object to its destination. From this I identified the problem was indeed with GetAngle.

In my main update I run b2World::step() then all of my game objects run their logic. It is at this point that my objects "accelerate" action calls GetAngle() and gets some weird results that seem to veer further and further off the faster the object is going and at higher speeds starts to flicker between two or more different locations. Yet later in my main rendering function calling GetAngle() returns correct data. Also I experimented with moving the physics step() to after I run logic on my game objects and started getting intermittantly bad GetAngle() data in both rendering and the accelerate action called in object logic code. It seems to me like calling GetAngle() to soon after a step is throwing the bad data. I'm not sure why timing would matter though or why it hasn't been noticed in other projects.

I played around with different shapes, sizes, densites, step intervals, step iterations, and nothing even slightly improved the problem. Any ideas? I can post some source, but I have to rip chunks out of context because my engine code has grown very long and complex.

Code:
void Accelerate::doAction( float deltaTime )
{
.....
   //normal way:  accelerate in the direction the body is facing
   // why is this returning bad data???
   float32 angle = user->body->getAngle();
   Vector2 direction = angleToVector( angle );
   //direction *= force;
   //direction *= 10.0f;
   //string str = user->getName() +" action angleToVector = "+ stringify(direction.x)+","+ stringify(direction.y);
   string str = user->getName() +" action angle = "+ stringify(angle);
   hgeCreate(HGE_VERSION)->System_Log(str.c_str());

   // Debug tool
   if (globalCam)
   {
      hgeCreate(HGE_VERSION)->Gfx_BeginScene();
      hgeCreate(HGE_VERSION)->Gfx_RenderLine(globalCam->screenX(user->body->getPosition().x), globalCam->screenY(user->body->getPosition().y),
         globalCam->screenX(user->body->getPosition().x + direction.x), globalCam->screenY(user->body->getPosition().y + direction.y), ARGB(180,0,255,0));
      hgeCreate(HGE_VERSION)->Gfx_EndScene();
   }

   user->body->body->ApplyForce(direction,Vector2(0,0));


Code:
// just updates the animation's frame in the engine
void Creature::RenderEx( Camera* cam )
{
.....

   if ( Physics::get()->drawEnabled )
   {
      if ( states["destination"] )
      {
         Vector2 dest = ( (State::Destination*) states["destination"] )->destination;
         hge->Gfx_RenderLine(cam->screenX(body->getPosition().x), cam->screenY(body->getPosition().y), cam->screenX(dest.x), cam->screenY(dest.y), ARGB(100,0,0,255));
      }   

      Vector2 direction = angleToVector(body->getAngle());

      //string str = getName() +" creature render angleToVector = "+ stringify(direction.x)+","+ stringify(direction.y);
      string str = getName() +" creature render angle = "+ stringify(body->getAngle());
      hgeCreate(HGE_VERSION)->System_Log(str.c_str());

      direction+= body->getPosition();
      hge->Gfx_RenderLine(cam->screenX(body->getPosition().x), cam->screenY(body->getPosition().y), cam->screenX(direction.x), cam->screenY(direction.y), ARGB(100,255,0,0));
   }
   
}


Code:
bool SimulationState::update(float dTime)
{
   //IMPORTANT! -- half of the update is in the parent class
   if (Parent::update(dTime))
      return true;

   //PHYSICS
   //static float frameLength = 1.0f/60.0f;
   //static float physicsTime = 0;
   //physicsTime += dTime;
   //if(physicsTime > frameLength)
   //{
   //   getWorld()->Step(frameLength, 5);
   //   physicsTime-= frameLength;
   //}

   //PHYSICS
   getWorld()->Step(dTime, 8);

   //!!! UPDATE ALL SIMS IN SIMULATION !!!
   root.update(dTime);

   // Continue execution
   return false;
}


Code:
void SimulationState::render()
{
   // Now we let the Gui Object perform its logic.
   gui->logic();

   // Next we begin a scene.
   hge->Gfx_BeginScene();
   hge->Gfx_Clear(0);

   //if (&quad)
   //{
   //   hge->Gfx_RenderQuad(&quad);
   //}
   //else throw GCN_EXCEPTION("terrain quad is missing!");

   for( size_t x = 0; x < background.size(); x++ )
      background[x]->render(*cam1);

   Objects->RenderEx(cam1);

   Physics::get()->draw();


   // Now we let the Gui Object draw itself.
   gui->draw();
   // Finally we end the scene causing the screen to be updated.
   hge->Gfx_EndScene();
   //hge->System_Log("render");
   
   //return false;
}
I'm not sure what's going on here.

Are the bodies fixed rotation? Are they rotating even with fixed rotation?

Why are you rotating the bodies manually? What are you using the engine for?
I'm using box2d to handle physics and I'm having problems with my isometric game setup. The players and buildings etc. interact with box2d bodies. The bodies are not using fixed rotation. For the players controls I'm rotating the bodies manually right now just to start simple. I was going to go the real world route and apply torque eventually but it was easier to make the players snap to the correct angle and not worry yet about a pure torque calculation where i would have to time things to avoid them overshooting their desired angle.
Here's a screenshot to illustrateImage

The real problem here is that between calls of step() the results of GetAngle() are changing, and not to anything I'm putting in manually with SetAngle(). I've confirmed this both with visual displays and a log file. It sounds like you don't have any idea why this would happen either. I'm kind of at a loss for ideas.
As a reminder, Erin, some other users reported that GetAngle doesn't return the same angle that you put in with SetXForm (error larger than rounding error). It's probably some discrepancy between the angle as given by m_xf and m_sweep, if those are both still around.
I've tried both "body->GetXForm().R.GetAngle();" and "return body->GetAngle();" with the same results. Also I've seen it go off by huge amounts... like around the completely opposite direction. Then magically when I call GetAngle later in the same frame it miraculously works again. If I switch my bodies to squares to make their angle more obvious and move my call to step() closer to the rendering code I can even see the squares freaking out in my b2DebugDraw. Meanwhile if my step() is called earlier in the frame by the time it gets to b2DebugDraw GetAngle() seems to have calmed down and the problem isn't apparent from b2DebugDraw. Maybe I can make a recording and post it on youtube or something.
More useful would be a testbed example that reproduces the problem. It's really hard to debug otherwise.
Are you using degrees or radians? Box2D uses radians. What are the typical values you are seeing?
Erin Catto wrote:
Are you using degrees or radians? Box2D uses radians. What are the typical values you are seeing?
Nothing in my program uses degrees. For my Accelerate::doAction() function I copied into my first post I use this function I should have copied before.
Code:
inline Vector2 angleToVector ( float radian )
{
   return Vector2( cos(radian), sin(radian) );
}

The values I'm getting are correct whenever an object is not in motion, but as it starts to accelerate the values get worse proportionate to the speed. I've added code to log the numbers I'm getting from different parts of the program.

Here a player starts moving and immediately you can see I set the angle to the desired -0.717601 to orient it towards its destination, but the very next frame the values start changing between the update and render portion of my code. At render the value is still -0.717601, but the value I'm getting at update is -0.716455. Only off by less than a thousandth of a radian but still weird considering this is between calls of step() and it shouldn't change.
Code:
...
player 1 creature render angle = 0
player 1 creature update angle = 0
player 1 creature render angle = 0
player 1 creature update angle = 0
player 1 is attempting action runToDestination
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 action angle = -0.717601
player 1 creature render angle = -0.717601
player 1 creature update angle = -0.716455
player 1 action angle = -0.716455
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = -0.717601
player 1 creature update angle = -0.715847
player 1 action angle = -0.715847
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = -0.717601
player 1 creature update angle = -0.714345
player 1 action angle = -0.714345
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = -0.717601
player 1 creature update angle = -0.714917
player 1 action angle = -0.714917
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = -0.717601
player 1 creature update angle = -0.712421
player 1 action angle = -0.712421
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = -0.717602
player 1 creature update angle = -0.712479
player 1 action angle = -0.712479
...

You can see a few frames later I'm still getting the correct values at render but the value is -0.717602 instead of -0.717601 because the player has already started to veer off course based on the numbers its using in its update/action code. At update meanwhile the angle is now about 5 thousandths of a radian off and it only gets worse as the object picks up speed.

Here's a clip of my log from about a second later.

Code:
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = 1.92335
player 1 creature update angle = 2.92335
player 1 action angle = 2.92335
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = 1.92017
player 1 creature update angle = 3.17017
player 1 action angle = 3.17017
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = 1.91618
player 1 creature update angle = 3.16618
player 1 action angle = 3.16618
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = 1.91219
player 1 creature update angle = 3.16219
player 1 action angle = 3.16219
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = 1.90819
player 1 creature update angle = 3.15819
player 1 action angle = 3.15819
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = 1.90418
player 1 creature update angle = 2.90418
player 1 action angle = 2.90418
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = 1.90097
player 1 creature update angle = 3.15097
player 1 action angle = 3.15097
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = 1.89695
player 1 creature update angle = 3.14695
player 1 action angle = 3.14695
player 1 is attempting action turnToDestination
player 1 is attempting action accelerate
player 1 creature render angle = 1.89293


You can see now the angle I'm getting during update is now more than a full radian off. Furthermore it seems to very suddenly jump between 2.9 and 3.1 more than once.


BorisTheBrave wrote:
More useful would be a testbed example that reproduces the problem. It's really hard to debug otherwise.

I can try reproducing the problem in a testbed example... but this bug is really obvious and showed up as soon as I switched my bodies to stop using fixed rotation and started using GetAngle in my program. So I'm assuming it doesn't show up under most conditions or it would have been noticed by now.

It might be a while before I get the chance, but I will try to reproduce it in a testbed example. Since it seems to be a timing thing I'll try making a testbed demo using deltaTime in step like my program and have it display the angle with glut immediately afterwards if that's possible.
Okay I've had a minor breakthrough. I did make a testbed example but didn't get it to replicate my bug from my program. At least didn't prove it with the assert statements in my implementation of the testbed experiment.
Code:
#ifndef GET_ANGLE_TEST_H
#define GET_ANGLE_TEST_H

class GetAngleTest : public Test
{
public:

   b2Body* testBody;
   float32 angleAfterStep;
   float32 angleBeforeStep;

   GetAngleTest()
   {
      angleAfterStep = 0.0f;
      angleBeforeStep = 0.0f;
      testBody = 0;

      const float32 k_restitution = 1.0f;
      
      {
         b2BodyDef bd;
         bd.position.Set(0.0f, 20.0f);
         b2Body* body = m_world->CreateBody(&bd);

         b2PolygonDef sd;
         sd.density = 0.0f;
         sd.restitution = k_restitution;

         sd.SetAsBox(0.1f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0f);
         body->CreateShape(&sd);

         sd.SetAsBox(0.1f, 10.0f, b2Vec2(10.0f, 0.0f), 0.0f);
         body->CreateShape(&sd);

         sd.SetAsBox(0.1f, 10.0f, b2Vec2(0.0f, -10.0f), 0.5f * b2_pi);
         body->CreateShape(&sd);

         sd.SetAsBox(0.1f, 10.0f, b2Vec2(0.0f, 10.0f), -0.5f * b2_pi);
         body->CreateShape(&sd);
      }
      
      {
         //b2PolygonDef sd;
         //sd.SetAsBox( 1.0f, 1.0f );

         b2CircleDef sd;
         sd.radius = 0.8f;
         sd.density = 1000.0f;

         b2BodyDef bd;
         bd.position.Set( 0.0f, 25.0f );
         b2Body* body = m_world->CreateBody(&bd);
         body->CreateShape(&sd);;
         body->SetMassFromShapes();

         testBody = body;
      }
      


      //for (int32 i = 0; i < 0; ++i)
      //{
      //   b2BodyDef bd;
      //   bd.position.Set(0.0f, 15.0f + i);
      //   bd.isBullet = true;
      //   b2Body* body = m_world->CreateBody(&bd);
      //   body->SetAngularVelocity(b2Random(-50.0f, 50.0f));

      //   b2CircleDef sd;
      //   sd.radius = 0.25f;
      //   sd.density = 1.0f;
      //   sd.restitution = 0.0f;
      //   body->CreateShape(&sd);
      //   body->SetMassFromShapes();
      //}

   }

   static Test* Create()
   {
      return new GetAngleTest;
   }

   float32 m_angularVelocity;
   float32   angle;

   virtual void GetAngleTest::Step(Settings* settings)
   {
      //float32 timeStep = settings->hz > 0.0f ? 1.0f / settings->hz : float32(0.0f);

      //if (settings->pause)
      //{
      //   if (settings->singleStep)
      //   {
      //      settings->singleStep = 0;
      //   }
      //   else
      //   {
      //      timeStep = 0.0f;
      //   }

      //   DrawString(5, m_textLine, "****PAUSED****");
      //   m_textLine += 15;
      //}

      uint32 flags = 0;
      flags += settings->drawShapes         * b2DebugDraw::e_shapeBit;
      flags += settings->drawJoints         * b2DebugDraw::e_jointBit;
      flags += settings->drawCoreShapes      * b2DebugDraw::e_coreShapeBit;
      flags += settings->drawAABBs         * b2DebugDraw::e_aabbBit;
      flags += settings->drawOBBs            * b2DebugDraw::e_obbBit;
      flags += settings->drawPairs         * b2DebugDraw::e_pairBit;
      flags += settings->drawCOMs            * b2DebugDraw::e_centerOfMassBit;
      m_debugDraw.SetFlags(flags);

      m_world->SetWarmStarting(settings->enableWarmStarting > 0);
      m_world->SetPositionCorrection(settings->enablePositionCorrection > 0);
      m_world->SetContinuousPhysics(settings->enableTOI > 0);

      m_pointCount = 0;

      angleBeforeStep = testBody->GetAngle();
      //compare to the reading immediately after the last step to make sure there is no change
      b2Assert(angleBeforeStep == angleAfterStep);

      //emulate SetAngle and ApplyForce usage from my program
      {
         testBody->SetXForm( testBody->GetPosition(), b2Random(-10,10) );
         testBody->ApplyForce( b2Vec2(b2Random(-10,10),b2Random(-10,10)), b2Vec2(0,0));
      }

      m_world->Step(b2Random(0.0f,0.02f), settings->iterationCount);
      angleAfterStep = testBody->GetAngle();


      //m_world->Validate();

      //if (m_bomb != NULL && m_bomb->IsFrozen())
      //{
      //   m_world->DestroyBody(m_bomb);
      //   m_bomb = NULL;
      //}

      if (settings->drawStats)
      {
         DrawString(5, m_textLine, "proxies(max) = %d(%d), pairs(max) = %d(%d)",
            m_world->GetProxyCount(), b2_maxProxies,
            m_world->GetPairCount(), b2_maxPairs);
         m_textLine += 15;

         DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d",
            m_world->GetBodyCount(), m_world->GetContactCount(), m_world->GetJointCount());
         m_textLine += 15;

         DrawString(5, m_textLine, "heap bytes = %d", b2_byteCount);
         m_textLine += 15;
      }

      if (m_mouseJoint)
      {
         b2Body* body = m_mouseJoint->GetBody2();
         b2Vec2 p1 = body->GetWorldPoint(m_mouseJoint->m_localAnchor);
         b2Vec2 p2 = m_mouseJoint->m_target;

         glPointSize(4.0f);
         glColor3f(0.0f, 1.0f, 0.0f);
         glBegin(GL_POINTS);
         glVertex2f(p1.x, p1.y);
         glVertex2f(p2.x, p2.y);
         glEnd();
         glPointSize(1.0f);

         glColor3f(0.8f, 0.8f, 0.8f);
         glBegin(GL_LINES);
         glVertex2f(p1.x, p1.y);
         glVertex2f(p2.x, p2.y);
         glEnd();
      }

      if (settings->drawContactPoints)
      {
         //const float32 k_impulseScale = 0.1f;
         const float32 k_axisScale = 0.3f;

         for (int32 i = 0; i < m_pointCount; ++i)
         {
            ContactPoint* point = m_points + i;

            if (point->state == 0)
            {
               // Add
               DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f));
            }
            else if (point->state == 1)
            {
               // Persist
               DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f));
            }
            else
            {
               // Remove
               DrawPoint(point->position, 10.0f, b2Color(0.95f, 0.3f, 0.3f));
            }

            if (settings->drawContactNormals == 1)
            {
               b2Vec2 p1 = point->position;
               b2Vec2 p2 = p1 + k_axisScale * point->normal;
               DrawSegment(p1, p2, b2Color(0.4f, 0.9f, 0.4f));
            }
            else if (settings->drawContactForces == 1)
            {
               //b2Vec2 p1 = point->position;
               //b2Vec2 p2 = p1 + k_forceScale * point->normalForce * point->normal;
               //DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
            }

            if (settings->drawFrictionForces == 1)
            {
               //b2Vec2 tangent = b2Cross(point->normal, 1.0f);
               //b2Vec2 p1 = point->position;
               //b2Vec2 p2 = p1 + k_forceScale * point->tangentForce * tangent;
               //DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
            }
         }
      }
   }
};

#endif

My next step was to comment out the ENTIRE update portion of my bugged program and replace it with code I copied directly from my testbed experiment and adapted it slightly like so.
Code:
      angleBeforeStep = testBody->body->body->GetAngle();
      //compare to the reading immediately after the last step to make sure there is no change
      if(angleBeforeStep != angleAfterStep)
         throw GCN_EXCEPTION("angleBeforeStep != angleAfterStep bla bla");

      //emulate SetAngle and ApplyForce usage from my program
      {
         testBody->body->body->SetXForm( testBody->body->body->GetPosition(), 1 );
         testBody->body->body->ApplyForce( b2Vec2(5,5), testBody->body->body->GetLocalCenter());
      }

      getWorld()->Step(dTime, 10);
      angleAfterStep = testBody->body->body->GetAngle();

Interestingly the assert statement wasn't picking up anything in this case either but a window i already had in my program that displays a bunch of stats was saying the players angle was steadily increasing until it hit about 1.75 just before it hit the boundaries of the simulation. Which is a pretty big number considering i set it to 1 every frame and I don't think I'm applying any force that should be rotating it.

Dropping this bit of code after the above portion just to make sure I wasn't crazy confirmed this.
Code:
      if (angleAfterStep > 1.1)
         throw GCN_EXCEPTION("where is this value coming from!!!");


So it seems I was changing the angle between steps all along because using the SetXForm() and ApplyForce() functions as I was using it, was changing the angle to unexpected values. The only problem being of course that I'm of the understanding that those functions as I've used them above really shouldn't do anything but keep the angle at 1, and not apply any torque, angular velocity, or angle to the contrary. I would be very grateful to anyone who can help me figure out where the malfunction is, be it in my head, or in my code, or in box2d.

p.s. Sorry for spamming your board with my craziness over this issue.
Ok so GetAngle works fine, but here's a testbed example that demonstrates the angles of bodies going completely haywire. The angle is manually set to 1, then a force is applied directly to the center of mass which shouldn't affect the angle. Still somehow the angle immediately goes above 2 radians!
Code:
#ifndef GET_ANGLE_TEST_H
#define GET_ANGLE_TEST_H

class GetAngleTest : public Test
{
public:
   b2Body* testBody;

   GetAngleTest()
   {
      testBody = 0;

      const float32 k_restitution = 1.0f;
      
      {
         b2BodyDef bd;
         bd.position.Set(0.0f, 20.0f);
         b2Body* body = m_world->CreateBody(&bd);

         b2PolygonDef sd;
         sd.density = 0.0f;
         sd.restitution = k_restitution;

         sd.SetAsBox(0.1f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0f);
         body->CreateShape(&sd);

         sd.SetAsBox(0.1f, 10.0f, b2Vec2(10.0f, 0.0f), 0.0f);
         body->CreateShape(&sd);

         sd.SetAsBox(0.1f, 10.0f, b2Vec2(0.0f, -10.0f), 0.5f * b2_pi);
         body->CreateShape(&sd);

         sd.SetAsBox(0.1f, 10.0f, b2Vec2(0.0f, 10.0f), -0.5f * b2_pi);
         body->CreateShape(&sd);
      }
      
      {
         //b2PolygonDef sd;
         //sd.SetAsBox( 1.0f, 1.0f );

         b2CircleDef sd;
         sd.radius = 0.8f;
         sd.density = 1.0f;

         b2BodyDef bd;
         bd.position.Set( 0.0f, 25.0f );
         b2Body* body = m_world->CreateBody(&bd);
         body->CreateShape(&sd);;
         body->SetMassFromShapes();

         testBody = body;
      }
   }

   static Test* Create()
   {
      return new GetAngleTest;
   }

   float32 m_angularVelocity;
   float32   angle;

   virtual void GetAngleTest::Step(Settings* settings)
   {
      uint32 flags = 0;
      flags += settings->drawShapes         * b2DebugDraw::e_shapeBit;
      flags += settings->drawJoints         * b2DebugDraw::e_jointBit;
      flags += settings->drawCoreShapes      * b2DebugDraw::e_coreShapeBit;
      flags += settings->drawAABBs         * b2DebugDraw::e_aabbBit;
      flags += settings->drawOBBs            * b2DebugDraw::e_obbBit;
      flags += settings->drawPairs         * b2DebugDraw::e_pairBit;
      flags += settings->drawCOMs            * b2DebugDraw::e_centerOfMassBit;
      m_debugDraw.SetFlags(flags);

      m_world->SetWarmStarting(settings->enableWarmStarting > 0);
      m_world->SetPositionCorrection(settings->enablePositionCorrection > 0);
      m_world->SetContinuousPhysics(settings->enableTOI > 0);

      m_pointCount = 0;

      float32 desiredAngle = 1.0f;
      //emulate SetAngle and ApplyForce usage from my program
      {
         testBody->SetXForm( testBody->GetPosition(), desiredAngle );
         testBody->ApplyForce( b2Vec2(10,10), testBody->GetLocalCenter());
      }


      float32 actualAngle = testBody->GetAngle();
      b2Assert (actualAngle - desiredAngle  < 1.0);

      m_world->Step(1.0f/60.0f, settings->iterationCount);

      actualAngle = testBody->GetAngle();
      b2Assert (actualAngle - desiredAngle  < 1.0);
      
   }
};

#endif

Should I post this on google code instead now that I've properly demonstrated the bug?

Original thread: https://box2d.org/forum/viewtopic.php?t=3756