简体   繁体   中英

How to rotate parent to move child in Unity3D?

I have a relatively complicated math problem I need to solve for a game I'm working on in Unity. I've tried a couple things but nothing has worked.

Basically, I need to apply an offset rotation (Quaternion) to a parent, where the result of this rotation is to move its child in a given direction.

To explain it better, the problem would be simple if it could be guaranteed that the parent's forward vector was pointed at the child. Then I would simply create a ghost position by adding the desired direction to the child, and then use a LookAt rotation to rotate the parent to look at that ghost position. (The child doesn't need to be put in a specific position, it just needs to move generally in that direction)

What makes this complicated is that A. the parent could be at any rotation, and B. the child could be at any position relative the parent.

For context, I'm working on a procedural animation system and I'd like to have the bones bend in the direction of the Agent's velocity. With the IK'd bones this is easy, just move the IK. But for the actual bones, I need a way to move a bone in a direction by rotating its parent's bone.

Thanks for any help!

First, we need to have the child's current position and the target position in the coordinate system of the parent. It sounds as if the child's position already is expressed in this coordinate system. Then, if the target position is in world coordinates, you simply do this with the inverse parent world transform:

pTargetLocal = parent.worldMatrix^-1 * pTarget

Once we have this, we want to find a rotation R , such that pCurrentLocal is rotated towards pTargetLocal . Assuming unit vectors (as rotations preserve lengths), this equals:

parent.worldMatrix * pTargetLocal = parent.worldMatrix * R * pCurrentLocal
                     pTargetLocal =                      R * pCurrentLocal

Once we have R , we just need to update parent.worldMatrix = parent.worldMatrix * R .

This can be solved by representing R in axis-angle format. The axis would be axis = Vector3.Cross(pCurrentLocal, pTargetLocal) and the angle is angle = Vector3.Angle(pCurrentLocal, pTargetLocal) . You can either calculate a quaternion or a matrix from these parameters and multiply it with the current parent transform.

I assumed that the rotation center is the origin of the parent's local coordinate system. You could also rotate about another center to incorporate a translation component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM