Align X axis of one object according to another

Hello guys, i’m currently working on a Climbing ledge system, and i’m almost done, but i’m having a problem to place the character on the right place when he grabs the ledge.
Currently, i’m using transform.rotation.eulerAngles to make my character face the ledge, and then i transform the positions z and y of my characters to match the ledge, and it works fine, just like Pic 1! but, if i rotate the platform, the character will match the global Z position from the center of the ledge ( just like Pics 2 and 3 ), and that’s obviously causes some errors. then, i decided to try another method:

After i rotate my character to face the ledge, i could make the X axis of my character match the X axis of the ledge ( see pic 4 ). but i don’t know how to make this… if its possible, can someone help me?
and if you guys can come up with a simpler solution, its fine too :slight_smile:

Assuming they are parallel you can do:

character.right = ledge.right;

If you want to do it over time:

var q = Quaternion.FromToRotation(character.right, ledge.right);
transform.rotation = Slerp(transform.rotation, q * transform.rotation, speed * Time.deltaTime);

Note this does not take into account front or back. That is, this aligns the ‘right’ vectors of both, but a ledge has two edges and your alignment will be 180 degrees different dependent on which edge is used. If this is an issue, you can check the angle:

var align : Vector3;
if (Vector3.Angle(character.right, ledge.right < 90)
    align = ledge.right;
else 
    align = -ledge.right;

var q = Quaternion.FromToRotation(character.right, align);
transform.rotation = Slerp(transform.rotation, q * transform.rotation, speed * Time.deltaTime);