- Home /
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 :)
Answer by robertbu · Oct 31, 2013 at 02:58 PM
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);
with transform.right it aligned them in the X axis, making them paralell, but after this, how can i make the local Z axis of them match? ( i guess its the local Z ), so my character doesn't go trought the platform or stays far away from it, i want it to have the exact local Z position of the ledge...
Just replace 'character.right' and 'ledge.right' with 'character.forward' and 'ledge.forward' in the code above.
transform.eulerAngles = ledgeatual.transform.eulerAngles;
transform.position.y = ledgeatual.transform.position.y;
transform.right = ledgeatual.transform.right;
transform.forward = ledgeatual.transform.forward;
I'm using this, but the transform.right and forwards makes no difference... the behaviour is the same even if i remove it.. why?
Your first line sets the rotations equal to each other:
transform.eulerAngles = ledgeatual.transform.eulerAngles;
So even without the rest of your code, they will be aligned. Note if you want to set rotations eqaual, it is better to do:
transform.rotation = ledgeatual.transform.rotation;
excellent answer, too bad I cannot upvote you 1000 points :D