How to align object's up vector with surface normal?

0 votes
asked Apr 13, 2015 in Programming by Gleny Student (480 points)

I want to rotate a game object so that its upward axis (+y) is aligned with another game object's surface normal in a editor script. I should also be able to specify an angle that describes the rotation around the surface normal, if that is possible somehow.

This is what I got so far inside my OnSceneGUI():

float angle = 24f;
GameObject obj;

RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000))
{
    Vector3 normal = hit.normal;

   // Rotate here
}

Thanks for the help!

1 Answer

0 votes
answered Apr 16, 2015 by Bugstacker Senior (4,800 points)
selected Aug 15, 2015 by Gleny
 
Best answer

You can solve this like that:

 

float angle = 24f;
// Distance along the normal direction
float distance= 0f;

GameObject obj;

RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000))
{
    Vector3 normal = hit.normal;

    Quaternion q1 = Quaternion.AngleAxis(rotation, normal);
    Quaternion q2 = Quaternion.FromToRotation(Vector3.up, normal);
    Quaternion quat =  q1 * q2;                    

    obj.transform.position = hit.point + normal * distance;
    obj.transform.rotation = quat;
}
Welcome to Bugstacker Q&A, where you can ask questions concerning Game Development, Programming and Design and receive answers from other members of the community.

Help for

...