# Align to Normal rotation issue

Hi all,

Sorry I swear this will be the last normal related question ( for at least a week or two ).
I set up this scene to demonstrate a problem I was having in a way more complicated scene.

I’m aligning to the surface of this mesh but I’d like to remove that rotation that is occurring on the y axis. Is there a nice way to do that? I was thinking maybe if there was a way to calculate the in normals and additively apply it to the rotation… Maybe??

Or maybe there are other ways to rotate to a normal. I’ve kinda hit a wall though, if anyone has any suggestions, it would be ace!

Thanks
Pete

Here’s the code I’m using in the example -

``````    public Transform OriginObj;
public Transform AlignTarget;
public Vector3 ContactNormal;
public float SearchDist;

void FixedUpdate(){
Vector3 forward = OriginObj.TransformDirection(new Vector3(0,-1,0)) * SearchDist;
Debug.DrawRay(transform.position, forward, Color.green);

RaycastHit hit;
if (Physics.Raycast(OriginObj.position, OriginObj.TransformDirection(new Vector3(0,-1,0)), out hit, SearchDist)){
AlignTarget.position = hit.point;
AlignTarget.rotation = Quaternion.FromToRotation(new Vector3(0,1,0),hit.normal);
}
}
``````

And the scene as a package in case anyone wants to check it -
http://www.peterleary.com/ForumFiles/Align Issue-BwFW3RHDe2.unitypackage

The hit.normal looks on local coordinate system.

Vector3 worldNormal = hit.collider.transform.localToWorldMatrix.MultiplyVector(hit.normal);
AlignTarget.rotation = Quaternion.FromToRotation(new Vector3(0,1,0),worldNormal);

I found this in another post but it’s useful code - it calculates the smoothed normal which might be handy for you:

``````public static Vector3 SmoothedNormal(RaycastHit aHit)
{
var MC = aHit.collider as MeshCollider;
if (MC == null)
return aHit.normal;
var M = MC.sharedMesh;
var normals = M.normals;
var indices = M.triangles;
var N0 = normals[indices[aHit.triangleIndex*3 + 0]];
var N1 = normals[indices[aHit.triangleIndex*3 + 1]];
var N2 = normals[indices[aHit.triangleIndex*3 + 2]];
var B = aHit.barycentricCoordinate;
var localNormal = (B[0] * N0 + B[1] * N1 + B[2] * N2).normalized;
return MC.transform.TransformDirection(localNormal);
}
``````

Hey thanks tonemcbride. That is really great for smoothing the result movement across the normals but not the rotation on the axis that Im trying to avoid.
Booiljoung, thanks for that, I tried adding that to my script and it turned out pretty much the same.
I think I need to approach it in a totally different way. I have a little more energy for it this morning so I’ll see what I can do!
Thanks for all the help though.

If you change this:

``````AlignTarget.rotation = Quaternion.FromToRotation(new Vector3(0,1,0),hit.normal);
``````

to use the Z axis instead:

``````AlignTarget.rotation = Quaternion.FromToRotation(new Vector3(0,0,1),hit.normal);
``````

it might work more like you intended.

1 Like