# Silverlight Animations along Arbitrary Mathematical Paths via Easing

By , 28 Aug 2011

## Introduction

Almost two years ago, a very interesting article was published explaining how to create an animation along an arbitrary path in Silverlight Animation along a Path for Silverlight. It also provides `DoubleAnimationUsingPath `and `PointAnimationUsingPath `classes that are similar to the corresponding WPF classes (unlike WPF, Silverlight does not have this functionality by default).

The algorithm for creating animations used in the above article, however, is quite complex and involves approximating the path curve by a connected series of line segments (flattening).

The algorithm presented here is much simpler yet achieves the same results, using Silverlight built-in Easing functionality. My purpose is not to create `DoubleAnimationUsingPath `and `PointAnimationUsingPath `classes mimicking WPF functionality - even though it is possible to create them using this approach - but rather to show how to create an animation along any mathematically defined path (e.g. a curve, a connected series of curves, or a connected series of line segments).

## Background

### The Demos

Let us start from the end. Here are the Silverlight demos that are built based on the code described in the article: Path Animation Demos.

Here are the demo snapshots:

### A Little Bit of Math

One of the mathematical definitions of Path states that a path on an `X`, `Y `vector plane is a set of points that satisfy the following equations: `x = X(t)` and `y = Y(t)`, where `X `and `Y `are functions (for connected paths, they have to be continuous and for smooth paths they should have a continuous derivative). In the equations above, '`t`' is a real parameter. Sometimes '`t`' can be defined to be proportionate to the distance between the current point of the path and the origin of the Path along the path: in that case, the path is uniform in a sense that the length of a path from between values `t1` and `t2` only depends only on `(t2-t1)`. Sometimes, however, uniform Path parameterization is not the most convenient and in this article I give examples with slightly non-uniform parameterization.

The above definition, together with the fact that we can use Easing functions for animating X and Y coordinates of e.g. translate transform of a Silverlight object, provide us with an easy way to create Silverlight animations along arbitrary mathematical paths without resorting to expensive techniques like approximation.

### Math Path Samples

The simplest path is a linear path described by the following set of equations:

• `x = xFactor * t + xOffset;`
• `y = yFactor * t + yOffset;`

Here are the path equations describing a circular path:

• `x = cos(2pt) * scalingFactor`
• `y = sin(2pt) * scalingFactor`

In this case, '`t`' is the angle. To make this path elliptic, one just needs to have different scaling factors for '`x`' and '`y`' coordinates, but then the uniformity of the parameterization is going to be broken.

### A Little Bit More Math (Easing Math)

Now, let us express the animations with Easing functions via math equations. I actually had to figure it out by conducting experiments (since I could not find it anywhere online). The following formula describes how an eased animation behaves in time:

`v = (V2 - V1)/T * f(t/T) + V1 `

Where '`v`' is the resulting animation value, '`t`' is the time parameter, '`T`' is the time period in question (either time between two frames in an animation with frames or time between '`To`' and '`From`' values in case of `DoubleAnimation`), `V2` and `V1 `are the animation values at the end and the beginning of the animation correspondingly at the absence of Easing and '`f`' is the Easing function. In the formula above, we assume a linear animation (not a spline one) and the default `EasingMode`.

In our code, below, we always set (`From `and `To `properties of `DoubleAnimation`) `V1 = 0`, `V2 = 1`. We also deal with normalized time, thus assuming that `T = 1`. Because of that, we can write:

`v = f(t) `

where '`t`' is the normalized time and `f(t)` is the `Easing `function.

## Using the code

Presented here are three Silverlight demos illustrating the above concepts.

### Single Point Path Animation Demo

This demo shows how to create a single object animation along an arbitrary mathematical path with animations along elliptic and Bezier curves shown as examples. The demo appears under the title "Single Point Path Animation Demo" and the corresponding code is located under `SinglePointPathAnimation `VS 2010 solution.

The solution code also introduces some generic classes that facilitate creating such animations: `GenericEasingFunction`, `OneDAnimation` and `TwoDAnimation`.

`GenericEasingFunction` is a simple implementation of `IEasingFunction` interface that exposes `EasingFunc` property, allowing to set the `Easing `function as a delegate/lambda expression.

`OneDAnimation` class provides a way to set `Easing `function on a `DoubleAnimation`.

`TwoDAnimation` consists of two `OneDAnimation` objects corresponding to '`X`' and '`Y`' coordinate animations of a `TranslateTransform`.

Here is how the code is used to create an animation along an elliptic path:

```// animation along an elliptic path
TwoDAnimation animation1 =
new TwoDAnimation
{
TheTranslateTransform = TheTranslateTransform1,
XFunction = (t) => Math.Cos(t * (2.0 * Math.PI)) * 50,
YFunction = (t) => Math.Sin(t * (2.0 * Math.PI)) * 50 * 1.5
};

animation1.XAnimation.From = 0;
animation1.XAnimation.To = 1;
animation1.YAnimation.From = 0;
animation1.YAnimation.To = 1;

Storyboard sb1 = new Storyboard();
sb1.Duration = TimeSpan.FromSeconds(4);
animation1.SetStoryboard(sb1);
sb1.RepeatBehavior = RepeatBehavior.Forever;
sb1.Begin();```

See MainPage.xaml.cs file.

Animation along a Bezier path is created in the same way, only with different `XFunction `and `YFunction `lambda expressions.

### Multiple Point Animations along Arbitrary Paths

We want to create an animation effect where multiple objects are spread (preferably uniformly) along an arbitrary path and where the animation makes those objects move along the path in the same direction as shown in the Silverlight demo above. This is achieved by creating multiple objects along a path shifted by a Delta along the '`t`' parameter with respect to the previous object on the path. The objects will be moving along the path by Delta and then repeat the movement from their origin. This will create an illusion of multiple objects moving along the path all the way to the end.

The demos of multiple point animations appear under the "Multiple Point Animation Demo" title. The corresponding VS 2010 solution is titled `MultiplePointsPathAnimation`.

More generic code is developed under this solution as described below.

We clearly need a factory that produces multiple objects of the same type (since we need to place multiple objects along a path). `ElementFactory` is a very simple example of such a factory that creates red colored dots. It also adds the created elements to their parent panel.

These different objects on the path will clearly have different animation functions. These animation functions will be produced by the shifts of the animation function that defines the movement along the whole path. To create such functions, from one function, we employ the `FuncWithShift` class. Its constructor receives the original function and the shift value and its property `ShiftedFunc` returns the shifted function.

There is a class `ShiftFuncFactory` that uses `FuncWithShift` to generate multiple shifts of a function. It has a property `CurrentShift` which can be changed to manipulate the shift value, while its property `ShiftedFunc` is returning the resulting shifted function. `ShiftFuncFactory` class assumes that the shifted function will only operate when the time parameter changes from `0` to Delta (this is to account for the fact that the object should only move to where the next object was located in the beginning of the animation (it should not move all the way to the end of the path). `ShiftFuncFactory` class also has `ExternalShift` property which allows shifting the whole path (I use it in the "Running Letters" demo to shift the letters with respect to each other).

Finally, class `ItemsAlongPathFactory` actually builds the animations within its `SetStoryboar` function. It uses its `XFunc` and `YFunc` properties to set the path functions and uses `ShiftFuncFactory` functionality to build the corresponding function shifts.

Here is how we create a multiple point elliptic animation within MainPage.xaml.cs file:

```// Elliptic path
Func<double, /> xFunc1 =
t => Math.Cos(t * (2.0 * Math.PI)) * 50;

Func<double, /> yFunc1 =
t => Math.Sin(t * (2.0 * Math.PI)) * 50 * 1.5;

ItemsAlongPathFactory itemsFactory1 =
new ItemsAlongPathFactory
{
TheElementFactory =
new ElementFactory
{
},
DeltaShift = 0.1,
XFunc = xFunc1,
YFunc = yFunc1
};
Storyboard sb1 = new Storyboard();

sb1.Duration = TimeSpan.FromSeconds(0.1);
itemsFactory1.SetStoryboard(sb1);
//sb.AutoReverse = true;
sb1.RepeatBehavior = RepeatBehavior.Forever;

sb1.Begin();```

Bezier path multiple point animation is created in the same way using different path functions.

### Running Letters Demo

I used the code and concepts described above to create the "Running Letters" demo. The demo simply runs the red dots along the paths specified by "`AWebPros`" letters. The corresponding code is located in "`RunningLetters`" VS 2010 project.

## Points of Interest

A new, simpler way of creating Silverlight animations along arbitrary mathematical paths using `Easing `functions has been described in this article. Additionally, this article applies this new approach to creating multiple objects along arbitrary paths animations.

## History

• 1st February, 2011: Initial post

 Nick Polyak Architect AWebPros United States Member
I have 15 years of experience developing enterprise software, starting from C++ and Java on UNIX and moving towards C# on Windows platforms.
I am fascinated by the new .NET technologies especially WPF, Silverlight and LINQ.
Recently I decided to make a move and start my own contracting consulting and mentoring company AWebPros.
I can be contacted via my web site awebpros.com or through my blog at nickssoftwareblog.com

Votes of 3 or less require a comment

 Search this forum Profile popups    Spacing RelaxedCompactTight   Noise Very HighHighMediumLowVery Low   Layout Open AllThread ViewNo JavascriptPreview   Per page 102550
 First Prev Next
 My vote of 5 gizi 24 Apr '13 - 2:29
 Re: My vote of 5 Nick Polyak 28 Apr '13 - 16:12
 Re: My vote of 5 gizi 29 Apr '13 - 19:27
 Hi I am having a problem creating a simple animation in Silverlight, to move an image (a car for example) around a rectangle track, so it turns at corners. So I have traslation + rotation. However as I cannot change a property more then once in a storyboard I find I need lots of code manipulation to achieve this. I wonder what way would you choose to do it? Thanks Gizi Sign In·View Thread·Permalink
 Re: My vote of 5 Nick Polyak 30 Apr '13 - 1:02
 Hi Gizi, one way to do it would be to use multiple animations so that when one of them ends the other starts. In my async-await article Task Parallel Library and async-await Functionality - Patterns of Usage in Easy Samples[^] I show how to turn animations into Tasks. The Tasks can be easily chained together. So what you can do is - use the code in the article to turn your animations into tasks and then chain them so that they perform one after another. Nick Polyak Sign In·View Thread·Permalink
 Re: My vote of 5 gizi 30 Apr '13 - 21:49
 Re: My vote of 5 Nick Polyak 1 May '13 - 3:37
 Corrupted file? ramos.fabian 26 Aug '11 - 10:51
 Re: Corrupted file? Nick Polyak 27 Aug '11 - 16:36
 Re: Corrupted file? ramos.fabian 28 Aug '11 - 11:42
 Re: Corrupted file? Nick Polyak 27 Aug '11 - 16:42
 Re: Corrupted file? Nick Polyak 28 Aug '11 - 5:59
 One query... Kunal_Chowdhury 1 Feb '11 - 18:09
 Re: One query... [modified] Nick Polyak 1 Feb '11 - 18:26
 I suspect that animating multiple objects along PathListBox'es path is not so simple. Perhaps I am wrong. Can you refer to some article? Or perhaps you can simply show how to create such animation here? To be more specific, I did see some animation examples where the whole PathListBox was moving, but I could not find any examples where some objects were moving along some path. See the article I was referring to in introduction. Nick Polyak modified on Wednesday, February 2, 2011 12:33 AM Sign In·View Thread·Permalink
 Re: One query... Kunal_Chowdhury 1 Feb '11 - 18:32
 Re: One query... Nick Polyak 1 Feb '11 - 18:49
 Thanks for the pointers. The animations are great indeed, but again I think they were created by modifying the path itself. Quote from your "making rocking animations" article states: "With animation, it's mostly trial and error so just jump in an remember that Edit > Undo is your best friend." Here the animation is determined by the mathematical path and does not have to be created by hand so to say. Nick Polyak Sign In·View Thread·Permalink
 Re: One query... Kunal_Chowdhury 1 Feb '11 - 18:58
 Nick Polyak wrote: but again I think they were created by modifying the path itself.   Not exactly. Once you have set the PathListBox with proper animation path, any data can traverse on that way very easily. No need to modify anything else or write.   Yes, there are some changes require in the UI front i.e. the path you need to create and to do this, you may need some help of Undo to do it in better way.   It's the choice of your requirement but creating it in the UI level is the easy way, I guess. Please Vote for the Articles and/or Posts that you like.Kunal Chowdhury (Microsoft MVP (Silverlight) | CodeProject MVP | Follow My Blog | Follow Silverlight-Zone | Follow Me @ Twitter) Sign In·View Thread·Permalink
 Re: One query... Nick Polyak 1 Feb '11 - 19:05
 Can you point me to some code that achieves it? Unfortunately I could not find any source code in the last two articles you've mentioned. What is animation path of PLB? is it different from its layout path? How do you make the data traverse the path? Thanks Nick Polyak Sign In·View Thread·Permalink
 Re: One query... Kunal_Chowdhury 1 Feb '11 - 19:22
 Re: One query... Nick Polyak 1 Feb '11 - 19:40
 Hey, the article you've mentioned does not deal with animations. I suppose you were referring actually to this article: Beginners Guide to Silverlight 4 PathListBox Control (Part–II). In this article, you indeed show how to create a circular animation on a circular path using Expression Blend. It is indeed very simple. But what if a path is not circular, e.g exponential or Bezier? Nick Polyak Sign In·View Thread·Permalink
 Re: One query... Kunal_Chowdhury 1 Feb '11 - 19:43
 Re: One query... Nick Polyak 1 Feb '11 - 19:46
 Re: One query... Kunal_Chowdhury 2 Feb '11 - 5:00