Payedimaunt
Payedimaunt

Reputation: 1070

How to rotate a local axis of an object to another object?

Using the following code I can rotate the local Z axis to another GameObject.

/// <summary>
/// Faces local Z axis to another target object.
/// </summary>
/// <param name="target">Target.</param>
private void FaceTo(GameObject target){
    float damping = 0.03f;
    var lookPos = target.transform.position - transform.position;

    var rotation = Quaternion.LookRotation(lookPos);

    transform.rotation = 
         Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping); 
}

the result during the Update method is the following:

Result

Now I need to face to the object using another axis, not the Z axis of my object; for example I would use the positive X axis for obtain this result:

enter image description here

How can I modify my script? Unfortunately I do not know the math of Quaternions and Vectors and I'm a bit confused.

Upvotes: 2

Views: 1943

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32597

You can just append another rotation:

var rotation = Quaternion.LookRotation(lookPos) * Quaternion.AngleAxis(-90, Vector3.up);

Upvotes: 2

Related Questions