Post helpful code for Box2d Flash!

Just wanted to create a topic for people to post helpful bits of code, or download links for larger chunks. I thought of this because I saw people talking on here about limiting the speed of objects, but I never saw any code (unless I missed it). Well it's not too complicated, but for really common stuff like this I figured it might at least save someone a little time. Also it's interesting to see how people do things differently.

Code: Select all

//assuming you have the following variable that actually contains a b2Body
var body:b2Body;
//and a speed limit, I think this may depend on the mass of your object
var speedLimit:Number;

var bodyVelocity:b2Vec2 = body.GetLinearVelocity();
if (bodyVelocity.Length() > speedLimit) {
   var limitVelocity:b2Vec2 = bodyVelocity.Copy();
   limitVelocity.Normalize();
   limitVelocity.Multiply(speedLimit);
   var velocityDifference:b2Vec2 = bodyVelocity.Copy()
   velocityDifference.Subtract(limitVelocity);
   body.ApplyImpulse(velocityDifference.Negative(),body.GetCenterPosition());
}
Here's my contribution. It's a function to auto-orient a body to point towards a target body. I'm using it in a little game to automatically orient gun turrents towards their assigned targets. The code's a little messy and can probably be refactored, but it gets the job done. It's meant to be part of an Actor class that has a body attribute storing the b2Body instance. The turnLeft/Right functions just call ApplyTorque() to the body.

Code: Select all

public function autoOrient(target:Actor):void{
   var shipPosition:b2Vec2 = this.body.GetCenterPosition()
   var targetPosition:b2Vec2 = target.body.GetCenterPosition()
   
   var targetAngle:Number = Math.atan2(shipPosition.y-targetPosition.y, shipPosition.x-targetPosition.x) - Math.PI/2
   if(targetAngle < 0){
      targetAngle += 2*Math.PI
   }
   
   var currentAngle:Number = this.body.GetRotation() % (2*Math.PI)
   if(currentAngle > Math.PI){
      currentAngle -= 2*Math.PI
   }else if(currentAngle < -Math.PI){
      currentAngle += 2*Math.PI
   }
   if(currentAngle < 0){
      currentAngle += 2*Math.PI
   }
   
   var angleDiff:Number = (targetAngle - currentAngle)
   if(angleDiff < -1.5*Math.PI){
      angleDiff += 2*Math.PI
   }else if(angleDiff > 1.5*Math.PI){
      angleDiff -= 2*Math.PI
   }
   
   // Only bother rotating if we're off by 5 degrees or so.
   // This prevents "jittering".
   if(Math.abs(angleDiff) > 0.08){
      if(angleDiff < 0){
         turnLeft()
      }else{
         turnRight()
      }
   }   
}

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