# Face forward direction of movement

I am trying to get an object like an arrow to point in the direction it is moving. I am using this code from the Roll a Ball tutorial. Any ideas?

``````public var force:float = 1.0;
public var simulateAccelerometer:boolean = false;

function Start()
{

iPhoneSettings.screenOrientation = iPhoneScreenOrientation.Landscape;
}

function FixedUpdate () {
var dir : Vector3 = Vector3.zero;

if (simulateAccelerometer)
{

dir.x = Input.GetAxis("Horizontal");
dir.z = Input.GetAxis("Vertical");
}
else
{

dir.x = -iPhoneInput.acceleration.y;
dir.z = iPhoneInput.acceleration.x;

if (dir.sqrMagnitude > 1)
dir.Normalize();
}

}

``````

Thanks

Use this:

``````transform.rotation = Quaternion.LookRotation(dir);

``````

Note that if you make the object always face in the direction of movement this way, it won't be rolling anymore (of course) so that may affect the physics if you were relying on a rolling behaviour.

You could instead still have a round collider that is rolling, and have your visible object be a child object of that, and use the LookRotation function on that child, so the visible child (without a collider) is pointing in the direction of movement while the invisible parent (with a collider) is rolling freely.

Edit: Actually, you may want to use this to avoid very fast rotations, or errors if the object is standing still:

``````if (dir != Vector3.zero) {
transform.rotation = Quaternion.Slerp(
transform.rotation,
Quaternion.LookRotation(dir),
Time.deltaTime * rotationSpeed
);
}

``````

Here’s another solution that will look in the direction the ball’s moving, not the direction of input. Good for attaching a hat/gun to the ball or something.

``````transform.position = ballGameObject.transform.position;
transform.LookAt(transform.position + ballGameObject.rigidbody.velocity);
``````
• Position this object to where the ball is.
• Add the ball’s “rigidbody.velocity” to this object’s position, and then look at it. (The velocity value gives a point offset from the center that you can look at.)

Now just make your arrow model a child of this GameObject. Move the Z position out as far as you want the arrow to appear.

In my case I’m working on a top-down 2D game and I need to rotate my bullet. The code is

``````transform.rotation = Quaternion.LookRotation(Vector3.forward, shootDirection);
``````