For 2D graphics WPF provides three classes for animating points: PointAnimation (for linear interpolation), PointAnimationUsingKeyFrames and PointAnimationUsingPath.
For 3D graphics WPF provides only two: Point3DAnimation (for linear interpolation) and Point3DAnimationUsingKeyFrames. There is no built in class for animating points over a path in three dimensions.
In this post I will show you a custom animation class that I wrote to partially fill that gap. In the next post I will put it to use in a 3D animation demo.
Requirement
Provide an animation class that enables the animation of a 3D point over a 3D path such that the path is defined by a 2D path and a constant value of Z.
You can probably extend this to include more exciting paths in 3D, but it does not directly support animation of a 3D point over any 3D path.
The Point3DAnimationUsingPath Class
public class Point3DAnimationUsingPath : AnimationTimeline
{
#region AnimationTimeline abstract overrides
public override Type TargetPropertyType
{
get { return typeof (Point3D); }
}
protected override Freezable CreateInstanceCore()
{
return new Point3DAnimationUsingPath { Z = this.Z };
}
#endregion
#region AnimationTimeline virtual overrides
public override object GetCurrentValue(
object defaultOriginValue, object defaultDestinationValue,
AnimationClock animationClock)
{
PathGeometry path = this.PathGeometry;
Point point;
Point tangent;
path.GetPointAtFractionLength(
animationClock.CurrentProgress.Value, out point, out tangent);
return new Point3D(point.X, point.Y, Z);
}
#endregion
public double Z { get; set; }
public PathGeometry PathGeometry
{
get { return (PathGeometry)GetValue(PathGeometryProperty); }
set { SetValue(PathGeometryProperty, value); }
}
public static readonly DependencyProperty PathGeometryProperty =
DependencyProperty.Register(
"PathGeometry",
typeof(PathGeometry),
typeof(Point3DAnimationUsingPath));
}
Point3DAnimationUsingPath has two public properties, a 2D PathGeometry and a double called Z. These two define a coplanar path in 3D space and need to be set on objects of this type before starting an animation.
As a custom animation class, Point3DAnimationUsingPath must also derive from AnimationTimeline and override the abstract CreateInstanceCore method and TargetPropertyType property.
As you can see, TargetPropertyType returns the type of Point3D indicating that the target of the animation created by this class will be a property of type Point3D. CreateInstanceCore simply returns a clone of this class.
The magic of this class happens in the GetCurrentValue method which is an override of a virtual method. It’s actually quite simple. I delegate the animation task to the 2D path, and return a 3D point with the Z value set to the Z property.
In the next post I will provide an application that uses Point3DAnimationUsingPath.