# Smoothly rotate ship in the direction of movement using lerp

Hello all first post ever!

I’ve been working on a project and need a little help understanding lerp.

The idea is for the player to click a location in space and have the ship rotate to that location. I’ve got that part down but now I want the ship to slowly list towards the direction of travel and list back when its nearing the desired rotation.

I’ve poked around the forums and couldn’t find what I was looking for.

Code is as follows:

``````public class PlayerMovement : MonoBehaviour {

private Ray moveRay;
private RaycastHit moveHit;
Vector3 targetDir;
Vector3 newDir;
public float tiltSpeed;
public float rotationSpeed;
public float speed = 0;
public GameObject movementTarget;
static float t = 0.0f;

// Update is called once per frame
void Update ()
{
//Move the ship forward according to speed
GetComponent<Rigidbody>().velocity = transform.forward * speed;

{
speed += .25f;
}

//Get user input for destination
if (Input.GetMouseButtonUp(0))
{
//Debug.Log("Mouse Clicked");
moveRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(moveRay, out moveHit, 100))
{
//Debug.Log("Shooting Ray");
if (moveHit.collider.CompareTag("NavPlane"))
{
movementTarget.transform.position = moveHit.point;
//Debug.Log("Ray Hit Setting Destination");
}
}
}

//Find the target direction
targetDir = movementTarget.transform.position - transform.position;
//Create a new rotation with the target direction
newDir = Vector3.RotateTowards(transform.forward, targetDir, rotationSpeed * Time.deltaTime, 0.0F);
//Execute rotation
transform.rotation = Quaternion.LookRotation(newDir);

//Need help here
//Find out which direction we are turning
Vector3 tiltVector = Vector3.Cross(targetDir, transform.forward);
//Debug.Log("Tilt Vector " + tiltVector.y);

//if we are turning left rotate to 30
if (tiltVector.y > 0)
{
transform.Rotate(Vector3.forward, Mathf.Lerp(0, 30, t));
t += 0.01f;
}
//if we are turning right rotate to -30
else if (tiltVector.y < 0)
{
transform.Rotate(Vector3.forward, Mathf.Lerp(0, -30, t));
t += 0.01f;
}
}
}
``````

This is not achieving the desired effect. The ship will slowly list towards the direction of travel but the t vairable gets too high. I’m not sure how to cap it or if it is even possible. I feel like I am not approaching the problem the right way. If lerp isn’t the best option here I am all about learning new techniques. Any help would be appreciated.

Cheers!

You could potentially cap `t` like this:

``````t = Math.Min(t + 0.01f, 1.0f);
``````