Simulating a missile (using the AS3 version)

I have a rectangular body of width 5 and height 15 representing a missile. When I apply any force to the missile, the missile flies through the air and falls back to the ground, but does not rotate. What I'm trying to say is, shouldn't the missile be pointing downwards during the descent?

I have already tried adding a heavier (denser) shape to the top of the missile body. But even this doesn't make the missile rotate in mid-air and behave like a real missile.

What do I need to do? Do I have to manually set the angular velocity of the body during it's flight?
Take a look at the ApplyForce example in the TestBed. You might have to get the SVN version.
Missile rotation during flight is aerodynamic in nature, so you'll really need to model those forces by hand. Even if Box2D did include these forces, there's a lot more at work than a tendency for objects to align with their directions of motion (they don't do this in general - if you throw a javelin without the exact proper amount of angular momentum, it will not rotate along with the motion; an arrow or missile is stabilized by the fins, I'm pretty sure, though the physics of all of this is quite complicated).

As Erin said, check out ApplyForce, but the basics of what you should do to hack a solution together: apply some torque on the missile to bring its rotation in line with its motion, and add a force that brings its motion in line with its rotation (if that makes sense). The details of this are up to you, but the dot and/or cross products of the direction of motion and the orientation of the missile will likely give you the factors you need to multiply drag forces by (along with some function of the velocity, depending on your tastes).
By 'ApplyForce TestBed Example', I assume you mean the /Examples/TestBed/Tests/ApplyForce.h (revision=56) while browsing the SVN repo.

I'm using the AS3 port, so I can't actually execute the ApplyForce.h file to see how it works. But I did see the code and couldn't see anything special that would make the body rotate during its flight.

From what I understand of the C++ code, pressing 'w' applies a force of 200 units in the -y direction.

Am I missing something here? Or do I need to have a look at an executed example?
The ApplyForce example shows how to apply forces to a body. Simulating the aerodynamics of a missile is up to you. But in the end, you will be applying forces to simulate the aerodynamics.
Erin Catto wrote:
Simulating the aerodynamics of a missile is up to you. But in the end, you will be applying forces to simulate the aerodynamics.


OK, so I'm going to try doing this on my own. But, I'm no physics expert.

ewjordan wrote:
the basics of what you should do to hack a solution together: apply some torque on the missile to bring its rotation in line with its motion, and add a force that brings its motion in line with its rotation (if that makes sense).


@ewjordan: Honestly, that doesn't make much sense to me. You seem to know what you are talking about. Could you please be a little more elaborate, if it is not much trouble?

A gist of my code:
Code:
// Define the gravity vector
var gravity:b2Vec2 = new b2Vec2(0.0, 2);

//missile shape definition
box.extents.Set(5 / m_physScale, 15 / m_physScale);
box.friction = 0.3;
box.density = 1;

//missile body definition
bd = new b2BodyDef();
bd.AddShape(box);         
bd.position.Set(60 / m_physScale, 340 / m_physScale);
missile = m_world.CreateBody(bd);


When the SPACE key is pressed, I want the missile to be 'launched'. The code for ApplyForce is below:
Code:
missile.WakeUp();
            
force = missile.GetWorldVector(new b2Vec2(30, -60));
point = missile.GetCenterPosition();

//Rotating the missile 45 degrees
missile.SetCenterPosition(point, 3.14/4);
            
missile.ApplyForce(force, point);


Somewhere before or after the ApplyForce command, you want me to have an ApplyTorque command. But I'm not sure how that works. Moreover, inside the ApplyForce function itself (in b2Body header file), isn't there a torque addition being done?
I can certainly try to help you work through this. Basically, my suggestion, in more detail, is to do something like the following (warning, I haven't tested any code):

1) Get the body velocity:
b2Vec2 velocity = body.GetLinearVelocity();

2) Get the body orientation as a vector:
b2Vec2 orientation;
orientation.Set( cos(body.m_rotation), sin(body.m_rotation) );

3) At this point, b2Dot(velocity, orientation) will give you the magnitude of the projection of the velocity on the orientation; if your missile had perfect grip on the air, this would be its new speed, directed along the orientation vector. Instead of setting the velocity to this value, though, it's probably better to pick a parameter, airGripFactor let's call it, and do the following:
float32 proj = b2Dot(velocity, orientation);
b2Vec2 targetVelocity = orientation * proj;
b2Vec2 force = (targetVelocity - velocity) * airGripFactor;
body.ApplyForce(force, body.m_position);

By tuning the airGripFactor you can alter how much the orientation of the object affects its path through the air.

4) Now we need to handle altering the rotation. This is pretty easy, too - the cross product of the orientation and the velocity will give us a velocity weighted measure of how much of a correction should be applied to the rotation, which we'll multiply by another parameter, say airTorqueFactor:
float32 perp = b2Cross(velocity, orientation);
float32 torque = perp * airTorqueFactor;
body.ApplyTorque(airTorqueFactor);

It's possible that as written airTorqueFactor would need to be negative, I'm not sure (sign issues are a pest). I have absolutely no idea what the numerical values of airTorqueFactor and airGripFactor should be, you'll have to play with them. One thing to note is that all of this assumes that at m_rotation = 0 the body is aimed directly to the right. You'll have to patch things up a little bit if that's not the case by adding an offset angle to the arguments of the trig functions in step 2).

You could skip step 3) if you don't want or need the orientation of the missile to affect its motion. Let me know if you have problems with any of this, to be honest I've never actually used this as written, so I very well could have made a mistake. Also, step 4 might cause instabilities, especially for high values of airGripTorque, I'm not entirely sure. It's possible that a damping term would need to be added (this is basically an angular spring, and I usually like to damp my springs), if that appears to be the case I can help you figure out how to add that in there.

If this is too complicated, there are simpler methods that might suit you, depending on what your application is - one that comes to mind is just to set the rotation equal to the direction of motion each frame, but that has drawbacks because it eliminates the possibility of realistic collisions. But it's a good option if the missile never has to bounce off of anything because it just explodes, so you might consider it. Another is to apply a drag force to the back end of the missile, which captures the guts of the reason things like arrows rotate to the right direction; this has the drawback of slowing down your object over time, though.
Hey, thanks a lot for taking the time to help me out. I honestly appreciate it.

My application, basically is a Tank game. I'm sure you would have seen such a game where two tanks shoot missiles at each other. The user needs to set the force and angle with which the missile is to be launched. So, effectively, the missile should explode on first contact with anything. So, realistic collisions (bouncing off of anything) are not necessary. So your last paragraph may hold a lot of relevance to what I need. What is the command to find the current direction of motion?

Anyway, say I want to implement your original solution: as I had said in my previous post, my missile needs to be launched when a key is pressed. The key press event handler executes just once. Currently, my code just applies a force to the missile and then watches the missile go land somehwere without further processing.

I may have understood your solution wrong here, but from what I see, your functions (steps 1, 2, 3, 4) need to be executed repeatedly till the missile hits ground, right? I just need confirmation that it is repeated executions, like, every frame during the missile's flight. I'm not sure exactly where I should implement your solution.

Thank you. Sorry for the trouble.
Yes, that's right, that would all need to happen once per time step.

If you just want to set the angle, you need to calculate what the angle of motion is. I'm pretty sure that you would want to use something like float32 velocityAngle = atan2( v.y, v.x ), where v is the linear velocity of the body (body.GetLinearVelocity()). Again, I might be off by a sign. Once you have that you could do one of the following:

1) Apply a correction torque:

float32 torque = torqueFactor * ( velocityAngle - body.m_rotation);
body.ApplyTorque(torque);

or

2) Set the angle directly

body.m_rotation = velocityAngle;

Again, this needs to be done every frame, wherever that's most convenient within your game loop.

Hope this helps!
In general I would prefer it if people don't set the position/rotation every time step since this will break continuous collision detection.

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