Move and Rotate Animation in Silverlight 3


In this article we will see how we can animate Move and Rotate functionalities of any UIElement.

Creating Silverlight Project

Fire up Visual Studio 2008 and create a new Silverlight 3 Project. Name it as RotationInCodeBehind.


In Silverlight Game programming sometimes the object needs to be moved or to be rotated. For those scenarios this sample application is dedicated.

Let's say we have an arrow that points to a specific direction and we have to move in the arrow displaying direction, how to move with animation! We are going to see in this article.

Let's add a Helper class called "TransformFunctions.cs" which will contain static methods that will help us animating the object while moving or rotating.

The following static methods are for moving and rotating animation.



Now let's design our page in Blend.

We will have one TextBox which will take user input as number to move positions and four buttons for specific commands such as Left, Right, Back and Move.

And the object we would move or rotate is an Image.


The following XAML is for your reference


As you see in above xaml, we have an Image which has the RenderTransformOrigin set to 0.5 and the TransformGroup contains the RotateTransform and TranslateTrasform as rotate and translate respectively.

Now we will go ahead and right code for respective click events. Let's start with the Left, Right and Back.

For safe rotation let's have an public integer value which is initialized to 360. And in the constructor let's have the rotation angle as 360.


Now Left Button click event handler.


Similarly Right Button click event handler.


And finally the Back Button click event handler.


Now go ahead and test the application. It should rotate accordingly.

Now the most important part is the move Button click, in this event handler we have to check the angleOfRotation and based on that we will move.

AS you have seen in the above code display we are rotating Left or Right is 45 degrees so we need to check with multiples of 45 degrees angles.

Let's have a switch case where the angleOfRotation is being checked.

Before that let's have four integer variables initialized to 0, such as stepX, stepY, distanceX and distanceY. These are required to remember the last position of the object.


Now run the application and you should be moving and rotating the image as required.

Hope this article helps. 

Up Next
    Ebook Download
    View all
    View all