Align Rectangle to movement direction.

Hi

i'm trying to create a nice looking animation for a flying rocket(my arrow is an weldjoint between an circle and a box)

i tried to auto-align it by making the explisive head heavy and the rest lighter, which looks quite good, but when i hit something it starts spinning, and actually i just want the tail to align to the direction of movement.

this is my current code:

Code: Select all

      Player p = rocket.getOwner();
      Vec2 norm = p.getCrosshair().getTarget().clone();
      Vec2 rocketStartPos = p.getCrosshair().getPosition();

      //  relevant stuff starts here
      CircleShapeBuilder csb = new CircleShapeBuilder(getWorld());
      csb.type(BodyType.DYNAMIC);
      csb.position(rocketStartPos.add(norm.mul(0.125f)));
      csb.radius(rocket.getRadius());
      csb.density(0.5f);
      csb.friction(0.003f);
      csb.userData(rocket); // append the user data for later
      // processing
      Body explosives = csb.build();

      BoxBuilder bb = new BoxBuilder(getWorld());
      bb.type(BodyType.DYNAMIC);
      Vec2 createPos = rocket.getOwner().getCrosshair().getPosition().sub(norm.mul(rocket.getRadius()));
      bb.position(createPos);
      bb.halfHeight(rocket.getRadius());
      bb.halfWidth(rocket.getRadius() * 1.5f);
      bb.density(0.05f);
      bb.friction(0.003f);
      bb.userData(rocket); // append the user data for later
      float radians = (float) Math.atan2(norm.y, norm.x);
      bb.angle(radians);
      Body rockedBody = bb.build();

      WeldJointDef jointDef = new WeldJointDef();
      jointDef.initialize(explosives, rockedBody, explosives.getWorldCenter());
      world.createJoint(jointDef);

      rocket.setBody(explosives); // set the body to my data-class

Code: Select all

Vec2 velocity = body.getLinearVelocity();
         float angle;
         float PI_2 = (float) (Math.PI / 2.0);
         if (velocity.x == 0) {
            angle = (float) (velocity.y > 0.0f ? 0.0f : Math.PI);
         } else if (velocity.y == 0) {
            angle = velocity.x > 0 ? PI_2 : 3 * PI_2;
         } else {
            angle = (float) (Math.atan(velocity.y / velocity.x) + PI_2);
         }

         if (velocity.x > 0.0f) {
            angle += Math.PI;
         }

         body.setTransform(body.getPosition(), angle);

thats my current code, which is better than nothing but not exactly what i want
I think you might be looking for
atan2(velocity.y, velocity.x)
...instead of
atan(velocity.y / velocity.x)

There is a useful diagram here, about halfway down the page on the right:
http://en.wikipedia.org/wiki/Atan2
atan2 works fine when i fire my missile to the right,
firing to the left makes the missile fly the wrong direction
beside that it aligns the same way as with Math.tan

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