Click here to Skip to main content
Click here to Skip to main content

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).

Building up on this foundation, this article additionally shows how to create a dots-running-along-an-arbitrary-path visual effect.

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
    {
	ThePanelToAddElementTo = Grid1
    },
    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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nick Polyak
Architect AWebPros
United States 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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membergizi24 Apr '13 - 2:29 
I found this code very useful!
GeneralRe: My vote of 5memberNick Polyak28 Apr '13 - 16:12 
Thanks!
Nick Polyak

GeneralRe: My vote of 5membergizi29 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
GeneralRe: My vote of 5memberNick Polyak30 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

GeneralRe: My vote of 5membergizi30 Apr '13 - 21:49 
Hi Nick.
Reading your TPL article, I also found we can use this pattern in Silverlight 5 by:
"Async Targeting Pack for Visual Studio 2012"
Thanks a lot for your help on my question,
Gizi
GeneralRe: My vote of 5memberNick Polyak1 May '13 - 3:37 
PleasureSmile | :)
Nick Polyak

QuestionCorrupted file?memberramos.fabian26 Aug '11 - 10:51 
The linked file seems to be corrupted Confused | :confused:
Thanks
AnswerRe: Corrupted file?memberNick Polyak27 Aug '11 - 16:36 
Thanks for bringing it to my attention. I'll try to replace it.
Nick Polyak

GeneralRe: Corrupted file?memberramos.fabian28 Aug '11 - 11:42 
Thumbs Up | :thumbsup:
 
Thank you for sharing it.
AnswerRe: Corrupted file?memberNick Polyak27 Aug '11 - 16:42 
I sent the editors the new source code attachment and asked them to put it in instead of corrupted file.
Nick Polyak

AnswerRe: Corrupted file?memberNick Polyak28 Aug '11 - 5:59 
Fixed. Thanks for bringing it to my attention.
Nick Polyak

QuestionOne query...mvpKunal_Chowdhury1 Feb '11 - 18:09 
Is this really require as this can be achieve easily using the PathListBox control?

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)

AnswerRe: One query... [modified]memberNick Polyak1 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

AnswerRe: One query...mvpKunal_Chowdhury1 Feb '11 - 18:32 
Have a look into some good articles here:
 
- http://blogs.xamlninja.com/silverlight/pathlistbox-adventures-radial-layout[^]
- http://www.kunal-chowdhury.com/2010/07/beginners-guide-to-silverlight-4.html[^]
- http://silverzine.com/tutorials/pathlistbox-text-on-the-path/[^]
- http://silverzine.com/tutorials/pathlistbox-making-rocking-animations/[^]
 
I think those are more simple and make your code clean. Let me know, if I understood your problem wrong.

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)

GeneralRe: One query...memberNick Polyak1 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

GeneralRe: One query...mvpKunal_Chowdhury1 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)

GeneralRe: One query...memberNick Polyak1 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

GeneralRe: One query...mvpKunal_Chowdhury1 Feb '11 - 19:22 
Hey,
 
I shared one of my article above. You may read it. I mentioned everything in detail using Expression Blend: http://www.kunal-chowdhury.com/2010/07/beginners-guide-to-silverlight-4.html[^][^]

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)

GeneralRe: One query...memberNick Polyak1 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

GeneralRe: One query...mvpKunal_Chowdhury1 Feb '11 - 19:43 
In that case, instead of creating the circle, just create the path using the Blend Path tool. The rest is similar.
I had one such link but not present currently. I will try to do a search in my database. It was showing how to animate a car in a path.

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)

GeneralRe: One query...memberNick Polyak1 Feb '11 - 19:46 
I understand the part about creating the path. But in that case animating rotation transform angle will not work. Looking forward to your sample.
Nick Polyak

GeneralRe: One query...mvpKunal_Chowdhury2 Feb '11 - 5:00 
Ok, I will try to post a sample for you in this weekend. BTW, take my 5 for your great work. Thumbs Up | :thumbsup:

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)

GeneralRe: One query...memberNick Polyak2 Feb '11 - 7:04 
Thanks Kunal!
Nick Polyak

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 28 Aug 2011
Article Copyright 2011 by Nick Polyak
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid