- Home /
Rotation to go from one direction to another?
I have a target direction say (0,1,0) and a current direction a transform is facing, say (0,-1,0), how can I calculate the rotation required to make the transforms direction (0,1,0) so that I can apply it with something like transform.Rotate((x,y,z))
The reason I'd like to do this is that I have a skinned character and I want to make him point in a direction of my choosing, unfortunately setting transform.forward on a bone does not necessarily mean he points in the right direction.
Ok I think I came up with a solution but it's not perfect, is it the correct way to do it or am I doing something wrong?
void LateUpdate()
(....)
Vector3 origin = transform.GetChild(0).position;
Vector3 currentDir = (transform.GetChild(0).GetChild(0).GetChild(0).position - origin).normalized; //direction based on outstretched arm, it's from hand to arm
Vector3 targetDir = (targetPos - origin).normalized; //target direction to point
transform.GetChild(0).rotation *= Quaternion.FromToRotation(targetDir, currentDir);
My current problem is the arm is still being affected by the parents rotations rather than just pointing, so it wobbles as its parent transform has rotations applied to it..
I can't find the exact formulas, you can do this with sine and cosine , you can also convert the unit vectors to eulerAngles, anyway normally I know this but right now I don't! http://www.jmargolin.com/uvmath/uvmath.htm
Use simply quaternion.Slerp: http://unitygems.com/quaternions-rotations-part-1-c/
It sounds like you are trying to write an I$$anonymous$$ solution - these are pretty difficult (I know I wrote 95% of one and then heard about mechanim which includes it!). Your problem may be a twist around the axis of the bone which you aren't fixing with the FromToRotation.
this question has got me confused, normally it's a lot easier to work with eulerAngles and transform.rotation, find the target.transform.rotation and the origin.transform.rotation and rotate the eulerAngles in between, like that you can control the child's transform by using local rotation and rotation.
Well I'd say a FromToRotation was the right solution in this case, given that the OP has a desired vector and an existing vector being updated every frame, it makes sense to do it like that.
@chillypacman you really need to cache those transforms rather than calling GetChild multiple times per frame.
Your answer
Follow this Question
Related Questions
Unity thinks my Quaternion is a Float 2 Answers
Rotate vector3 relative to another vector3 1 Answer
Copy Rotation Direction only on Y Axis. 1 Answer
Rotate object to target position 1 Answer