Unity3D Slerp rotation speed

Agostino picture Agostino · Dec 2, 2013 · Viewed 12.2k times · Source

I'm using Unity3D. I'd like to rotate an object to face the direction of the mouse pointer, but allow a maximum rotation speed, like "max 100 degrees per second".

There is an example in the doc, but it does not do what I want.
I think the Time.time should be Time.deltaTime, and I can't really understand what the last parameter does. Is it supposed to be the number that gets summed to the start vector?
http://docs.unity3d.com/Documentation/ScriptReference/Quaternion.Slerp.html

Also, I can't really understand what the last parameter does. Is it a time for the rotation?

The code I'm using now

Plane plane = new Plane(Vector3.up, 0);
float dist;
void Update () {
    //cast ray from camera to plane (plane is at ground level, but infinite in space)
    Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
    if (plane.Raycast(ray, out dist)) {
        Vector3 point = ray.GetPoint(dist);

        //find the vector pointing from our position to the target
        Vector3 direction = (point - transform.position).normalized;

        //create the rotation we need to be in to look at the target
        Quaternion lookRotation = Quaternion.LookRotation(direction);

        //rotate towards a direction, but not immediately (rotate a little every frame)
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
    }
}

I think the weak spot is in the third parameter of the Slerp, but I can't figure out what to put there.

Answer

Agostino picture Agostino · Dec 2, 2013

This code works, but I'm not sure it's 100% correct.

Plane plane = new Plane(Vector3.up, 0);
float dist;
void Update () {
    //cast ray from camera to plane (plane is at ground level, but infinite in space)
    Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
    if (plane.Raycast(ray, out dist)) {
        Vector3 point = ray.GetPoint(dist);

        //find the vector pointing from our position to the target
        Vector3 direction = (point - transform.position).normalized;

        //create the rotation we need to be in to look at the target
        Quaternion lookRotation = Quaternion.LookRotation(direction);

        float angle = Quaternion.Angle(transform.rotation, lookRotation);
        float timeToComplete = angle / rotationSpeed;
        float donePercentage = Mathf.Min(1F, Time.deltaTime / timeToComplete);

        //rotate towards a direction, but not immediately (rotate a little every frame)
        //The 3rd parameter is a number between 0 and 1, where 0 is the start rotation and 1 is the end rotation
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, donePercentage);
    }
}