Charles Petzold



Animation and Natural Law

June 16, 2006
Roscoe, NY

I've been thinking recently about how to get XAML animations to behave more in accordance with natural laws, such as the conservation of energy, so they don't go on forever like a perpetual motion machine. I'd like to see animations "wind down" as they would in real life in the presence of friction and air resistance.

Here's one stab at such a thing. WindDownPendulum.xaml is a pendulum whose arc starts off at ±30° and over the course of 5 minutes goes down to 0°. (The decrease is linear when it should probably be exponential, but this is a first try.)

Here's the listing:

Yep, it's my favorite technique of using composite transforms to perform arbitrary math. Toward the top I have an invisible FrameworkElement whose sole role is to host a composite TransformGroup. The RotateTransform has its Angle property animated from 0° to 360° over two seconds, and repeated for five minutes. Thus, the M11 property of the resultant Matrix object is the cosine of that angle, which, of course, goes from 1 to 0 to -1 to 0 back to 1 every two seconds.

The other transform in the TransformGroup is a ScaleTransform, with its animated ScaleX property slowly decreasing from 30 to 0 over the course of five minutes. This value is effectively multiplied by the cosine of the angle, so in the composite transform, the M11 property of the Matrix object is this decreasing scaling factor times the cosine of the animated angle. This is what's used to set the rotation angle of the pendulum object.