# Quaternian FromToRotation is rotating in wrong direction.

I’m trying to write a script so that an object can seamlessly transition between running on the ground and running on a wall.

The way I’ve gone about this is MOSTLY working, by using the three OnCollision functions (Enter, Stay, and Exit) calling a function to re-orient the transform’s ‘up’ to match the normal of the surface they collide with. The problem I’m having is sometimes the rotation isn’t working like I expect it to:

when running on the “floor” and hitting the wall, the object rotates correctly so that it’s facing towards the sky, but when walking down off the wall into the ground the object rotates (approximately) 180 degrees around the x and y axis, so that it’s “top” is now pointed at the wall it was just walking on, and it’s “face” is on the ground it just collided with. (I say approximately because the two axis are orienting to the normals of the two surfaces, even if the collision is at an angle.) I am unsure what’s causing this bug, as other collisions seem to work fine. Here’s the relevant code from my script:

``````void WallStick(Collision collision)//TODO fix weird angle rotations.
{
//Acquire the impact location and normal
Vector3 impactPoint = collision.contacts[0].point;
Vector3 impactNormal = collision.contacts[0].normal;

impactPoint -= impactNormal;//take a step back from the impact point along the normal

RaycastHit hitInfo;
if (collision.collider.Raycast(new Ray(impactPoint, impactNormal), out hitInfo, 2))
{
//If the raycast finds a surface, we use that surface's normal, instead of our impact one.
impactNormal = hitInfo.normal;
}
else
{
Debug.Log("Error: Raycast didn't find surface to land on.");
}
Quaternion rotate = Quaternion.FromToRotation(transform.up, impactNormal);
testVector = impactNormal;//this is a debugging variable, I'm watching in the inspector.
transform.rotation = rotate;
}
``````

EDIT: I actually spent the weekend thinking about it, and ended up coming up with a solution that didn’t use Quaternions:

``````Vector3 newAxis = Vector3.Cross(transform.up,impactNormal);
float angle = Vector3.Angle(transform.up,impactNormal);
transform.RotateAround(transform.position,axis,angle);
``````

This resolved my problems.

1 Like

You say:

``````Quaternion rotate = Quaternion.FromToRotation(transform.up, impactNormal);
transform.rotation = rotate;
``````

You ‘set’ the FromToRotation to the rotation.

Thing is, the FromToRotation is the amount of change in rotation that would go from up to impactNormal, not the rotation one should be to align with impactNormal.

Try saying something like:

``````transform.rotation *= rotate;
``````

Appending the needed change onto the current rotation.

1 Like

Thank you!