This will work if all you're concerned about is the translation part of each bone, but it is more common to represent your bone structure as a transformation matrix tree, which is probably the most popular way to do Forward Kinematics.
Define a Node
as follows:
class Node
{
Transform localTransform;
Node parent;
List<Node> children;
// Computes the global transform of the node with respect to the world.
Transform ComputeGlobalTransform()
{
if (parent == null) return localTransform;
else return parent.ComputeGlobalTransform() * localTransform;
}
}
A Link
is a Node
that has mesh geometry. A Joint
is a node that connects two links, and rotates around its Z
axis.
class Link : Node
{
Mesh geometry;
}
class Joint : Node
{
void SetJointAngle(float value)
{
// The local transform is a rotation around the Z axis by convention.
// Make sure to preserve the translation part of the transform.
localTransform.SetRotationPart(Matrix.CreateRotationZ(value));
}
}
You can make more complicated joints such as prismatic and ball-in-socket joints fairly easily this way. Representing your links and joints as transforms rather than just a direction and a length also disambiguates the rotation part of your skeletal animation system. It also allows you to offset links in an arbitrary way.