June 12th, 2009
Using projection to build a 3D carousel in Silverlight 3
10 Comments, All Silverlight Examples, Silverlight 3 tutorials, Silverlight Blend Tutorials, Silverlight C# Tutorials, Silverlight Effects, by Gavin Wignall.In the below example I used the new projection properties in Silverlight 3 to build a 3D image carousel. Moving the mouse left to right controls the speed and direction of the carousel. Moving the mouse up and down changes the opacity of the carousel, allowing you to see what is going on behind the carousel.
The ‘how to’ bit
To start with I have placed 6 images inside Blend and used the projection properties to offset them against each other to form a 3 dimensional hexagon. I do this by changing 2 projection properties:
CenterOfRotationZ=”-173″
RotationY=”60″
I use the ‘CenterOfRotationZ’ value to move the center point away from each image plane. This value needs to be the same on each of the 6 images I use in order to get them to match up at the edges. I then use the ‘RotationY’ value to change the angle of each image, as I have 6 images each image is rotated by a factor of 60 degrees (6 x 60 = 360 degrees).
I then place an x:Name on each images projection tag as seen in the below example:
<PlaneProjection x:Name=”Image1Projection” CenterOfRotationZ=”-173″ RotationZ=”0″/>
This will allow me to easily change the angle of each image dynamically in the C#.
In the C# I set up a listener to monitor the mouse movement and store the values in ‘pt’:
void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
{
pt = e.GetPosition(LayoutRoot);
}
Next I set up a CompositionTarget.Rendering function so that I can update my 3 dimensional carousel constantly. I use the mouse X co-ordinates to change the speed and direction of the carousel and the mouse Y value to change the opacity:
void CompositionTarget_Rendering(object sender, EventArgs e)
{
Image1Projection.RotationY += ((pt.X – (LayoutRoot.ActualWidth / 2)) / LayoutRoot.ActualWidth) * 10;
Image2Projection.RotationY += ((pt.X – (LayoutRoot.ActualWidth / 2)) / LayoutRoot.ActualWidth) * 10;
Image3Projection.RotationY += ((pt.X – (LayoutRoot.ActualWidth / 2)) / LayoutRoot.ActualWidth) * 10;
Image4Projection.RotationY += ((pt.X – (LayoutRoot.ActualWidth / 2)) / LayoutRoot.ActualWidth) * 10;
Image5Projection.RotationY += ((pt.X – (LayoutRoot.ActualWidth / 2)) / LayoutRoot.ActualWidth) * 10;
Image6Projection.RotationY += ((pt.X – (LayoutRoot.ActualWidth / 2)) / LayoutRoot.ActualWidth) * 10;
image1.Opacity = (pt.Y / LayoutRoot.ActualHeight) * 0.5 + 0.5;
image2.Opacity = (pt.Y / LayoutRoot.ActualHeight) * 0.5 + 0.5;
image3.Opacity = (pt.Y / LayoutRoot.ActualHeight) * 0.5 + 0.5;
image4.Opacity = (pt.Y / LayoutRoot.ActualHeight) * 0.5 + 0.5;
image5.Opacity = (pt.Y / LayoutRoot.ActualHeight) * 0.5 + 0.5;
image6.Opacity = (pt.Y / LayoutRoot.ActualHeight) * 0.5 + 0.5;
}
Grab the code
As always you can grab the code source here.