pyehouse
6Sep/110

Set Up Constant Speed in box2d

This brief tutorial will show you how to set up dynamic objects with a constant speed in box2d. It assumes you have a basic understanding of how to set up a box2d project with cocos2d.

As you are no doubt aware, the box2d physics engine is a wonderful tool for creating a virtual world filled with objects that interact in a way analagous to the real world. In this world gravity, friction (including rotational friction), inertia and momentum are all simulated.

But what of the concept of cruise control? You know, you set a speed and then the target continues to try to match that speed. You might control the vector direction in some other method, but the speed is intended to remain constant. How do you do that? That's what we're going to take a look out now.

Conceptually, what we want to do is measure our current speed on each update cycle and then fire an impulse of the appropriate size and direction in order to nudge us up to (or down to) speed. What we specifically do not want to do is simply call SetLinearVelocity(). Why not, you may ask. The problem is that doing so essentially tells the box2d engine "Hey, ignore whatever you *think* should be happening to that body. Here's the actual velocity." Instead, what we want to do is tell the box2d engine, "See that body over there? I want you to add this new impulse to it and factor that in along with everything else." This lets the box2d engine take the entire model and any ongoing interactions into account rather than dropping everything and running with the new values.

Because I'm taking code out of my game Centripetal, I don't have a full project with a demo set up to show you what I'm talking about. But I will pull out the pertinent bits and provide some illumination on what I'm doing.

Before we get started, remember that box2d is a physics simulator only. It does not display graphics. b2Body objects do have a UserData attribute which is a void* and which can therefore store a pointer to, for example, a CCSprite. Likewise, you can also create a CCSprite subclass which has a b2Body* member and thus the two could refer to one another. I will leave the pointer management concerns to you based on your own implementation.

In my case, I have a CCNode subclass which has member pointers to both the b2World and CCSprite objects.

@interface BodyNode : CCNode
{
	...
	b2Body* body;
	CCSprite* sprite;
	...
}
@property (readonly, nonatomic) b2Body* body;
@property (readonly, nonatomic) CCSprite* sprite;
...
@end

There's more to it, but that's enough to get us going here. Now let's focus on our CruiseControl object. We're going to subclass BodyNode for this and add a little to it:

@interface CruiseControl : BodyNode
{
	...
	float speed;
	...
}
@property (nonatomic) float speed;
...
@end

We've got a BodyNode subclass to which we have added a speed member. Why speed? Why not a b2Vec? We don't want a steady direction, just a steady rate of movement. We want the box2d engine to bounce us around and change our direction but we want to know just how fast we should be moving and try to nudge ourselves just enough, but in the current direction, in order to achieve that. Let's so how we do it:

-(id) init
{
	if ((self = [super init]))
	{
		...
		[self scheduleUpdate];
	}
	return self;
}

Okay, the first thing you'll see is that, among other things in init, I'm scheduling an update callback. This doesn't have to happen in init, but it's a convenient place to do so. Note that this is a subclass of BodyNode which has a pointer to the CCSprite we will ultimately be moving around in cocos2d. The update will occur on our BodyNode subclass and not directly on the CCSprite we contain.

-(void) update:(ccTime)delta
{
	b2Vec2 curvel = body->GetLinearVelocity();
	if (curvel.Length() < self.speed || curvel.Length() > self.speed + 0.25f)
	{
		float curspeed = curvel.Normalize();
		float velChange = self.speed - curspeed;
		float impulse = body->GetMass() * velChange;
		curvel *= impulse;
		body->ApplyLinearImpulse(curvel, body->GetPosition());
	}
}

There may be more going on inside your update method (there is in mine in fact), but what you see here is the nuts and bolts of the cruise control concept. We first retrieve the current velocity which is a vector with scale equal to current speed. We check that speed against our desired speed. If it is too low or if it is too high, we want to apply an impulse.

Note that I have a bit of a fudge factor. You are dealing with floating point numbers and the usual lack of precision that entails. You can play with your fudge factor as you like. Maybe you're okay with being a little slower but no faster. Maybe you don't mind a little wiggle room in either direction. You can alter that to your heart's content.

So if we need to apply an impulse, we first normalize our current vector of movement. That gives us the direction with a factor of 1.0f which conveniently allows us to reuse the vector by multiplying it by our speed to get what we need. We calculate our speed by simply subtracing the current speed from our desired speed. Note that if we are moving too fast, this gives us a negative value. This is important in the next step as we multiply by the body's mass to get the needed scale to apply to the vector to give us our new direction. In the case of excessive speed, this becomes a negative value which reverses the vector for purposes of applying the impulse. Finally, we apply the impulse to our body at its location, allowing the physics engine to nudge us enough to get us back to the correct level of speed.

Naturally, you can play around with this as much as you like. You can alter the scheduled update to call whichever method you prefer. You can alter the frequency of the scheduled callback too. Or if you prefer, you could conceivably eliminate the update callback on your BodyNode subclass by using the box2d processing loop to watch for your CruiseControl object and perform your check at that time. Regardless, you now have a simple method of setting up cruise control for your box2d objects.

An additional note concerning gravity: When developing Centripetal, I set the simulator up with no gravity as I was simulating a top down view of a frictionless surface. I didn't need gravity. The problem you will face when adding gravity is that if the gravity is intense enough compared to your desired speed, even with constant impulses to push the object along it won't be enough to counteract the gravitational pull between steps. So your object might end up slinking around on the bottom of your simulation view rather than moving about freely. If the gravity is low enough relative to the desired speed, then the steady stream of impulses coming each step should be enough to let you fly.