# How can I rotate a rigid body based on its velocity?

Hi,

I have a tank that can fire a projectile(rigidbody) at an angle and force specified by the player. A pretty basic artillery game mechanic. The projectile fires in the correct direction but at the moment, left to the physics engine, the projectile(which is a capsule at the moment) doesn't rotate or "point" in the direction of travel as it moves through the air.

Does anyone know how I can achieve this effect?

Thanks

UPDATED 27/12/10

TankControl.cs (attached to the tank - projectile instantiation Method) shellSpawn is an empty gameobject that is a child of the tank gun barrel to spawn the projectile from.

``````void Fire() {
//set the position and rotation of the projectile the the shell spawn point
Vector3 position = shellSpawn.position;
Quaternion rotation = shellSpawn.rotation;

GameObject firedProjectile = (GameObject)Instantiate(shell, shellSpawn.position, shellSpawn.rotation);

firedProjectile.rigidbody.AddRelativeForce(new Vector3(0,1,0) * gunPower, ForceMode.Impulse);
}

``````

Projectile.cs (attached to projectile prefab - Update Method)

``````void Update () {
transform.rotation = Quaternion.LookRotation(rigidbody.velocity);
}

``````

`transform.rotation=Quaternion.SetLookRotation(velocity);`

This will set your rotation in the exact same direction that you are moving in. This assumes that you have a Vector3 velocity which you are using. It seems a fair assumption, all things considered.

Here’s the code that worked for me:

``````transform.rotation = Quaternion.LookRotation(rigidbody.velocity);
``````

//rotates rigidbody to face its current velocity
public void RotateToVelocity(float turnSpeed, bool ignoreY)
{
Vector3 dir;
if(ignoreY)
dir = new Vector3(rigidbody.velocity.x, 0f, rigidbody.velocity.z);
else
dir = rigidbody.velocity;

``````	if (dir.magnitude > 0.1)
{
Quaternion dirQ = Quaternion.LookRotation (dir);
Quaternion slerp = Quaternion.Slerp (transform.rotation, dirQ, dir.magnitude * turnSpeed * Time.deltaTime);
rigidbody.MoveRotation(slerp);
}
}
``````