Rotating objects attached to other objects

丶灬走出姿态 提交于 2019-12-02 04:20:29

The transformation you're looking for is this:

Matrix positionRotationMatrix = Matrix.CreateTranslation(-parentPosition) 
                               * Matrix.CreateFromQuaternion(parentRotation) 
                               * Matrix.CreateTranslation(parentPosition);
Vector3 translation = Vector3.Transform(parentPosition + relativePosition,
                               positionRotationMatrix);

You define your world matrix with the new sub-objects position (translation variable):

Matrix worldMatrix = Matrix.CreateScale(scale)
                * Matrix.CreateFromQuaternion(rotation)
                * Matrix.CreateFromQuaternion(parentRotation)
                * Matrix.CreateTranslation(translation);

To demonstrate, here's a cube (parent) that is being rotated around it's position, with an arrow whose position and rotation are defined in relation to its parents position and rotation. The arrow follows the cubes rotation, and rotates around it's Z axis independently.

Values used for the demonstration:

parentPosition = Vector3(-1.1f, 0f, -2); //cube
relativePosition = Vector3(0, 0, -3); //arrow
parentRotation = Quaternion.CreateFromRotationMatrix(
                       Matrix.CreateRotationZ(angle) 
                     * Matrix.CreateRotationY(angle) 
                     * Matrix.CreateRotationX(0.5f));
rotation = Quaternion.CreateFromYawPitchRoll(0f, 0f, angle);
angle += 0.05f;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!