June 20th, 2009

Shadow effect using 3D projection in Silverlight 3

All Silverlight Examples, Silverlight 3 tutorials, Silverlight C# Tutorials, Silverlight Effects, by Gavin Wignall.

In the below example I use the new projection properties in Silverlight 3 to produce a realistic 3D shadow upon a sphere based on the mouse position on screen.

In my previous 3 posts I played with the projection property as the primary effect. In this example I wanted to show how the projection property can be used as a more subtle effect, in this case a shadow based on the users mouse position. To view the previous 3 posts on projection please view the links below:

Controlling Projection in Silverlight 3

Using projection to build a 3D carousel in Silverlight 3

Creating a 3D cube with images in Silverlight 3

The ‘how to’ bit

There are two effects that I create in the above example. The first is the lighting and the second is the shadow.

The first step is to run an event everytime the mouse is moved. Then to create the lighting effect, I first take the mouse position value and I use a small equation to give me a value that I can apply to a radial gradient’s ‘GradientOrigin‘ value. To control this i place an x:Name in the XAML called “lightAngle“:

<RadialGradientBrush x:Name=”LightAngle” GradientOrigin=”0.258,0.253″>

To create the shadow effect I use the  new projection properties given to us in Silverlight 3. I have drawn an ellipse with a radial gradient fill that goes from black to transparency. I then use the projection values in Blend to make the ellipse look like it is the shadow of the orignial red ball graphic. To animate the shadow I first take the mouse position value and use a series of equations to convert the values to apply to the projection globalOffest values of  LocalOffsetX and LocalOffsetY.

The tricky bit

To get the shadow to lie in the correct position we need to tell the LocalOffsetX value to point in the opposite direction to the mouse position. To do this we have to reverse the original value taken from the mouse. We can do this using the following equation:

Mouse X position = A

A = (A – (A * 2)) + 1

or in my example (where Mouse X = pt.X)

pt.X -= (pt.X * 2);

pt.X += 1;

Grab the code

As always you can grab the source here.

Back Top

Responses to “Shadow effect using 3D projection in Silverlight 3”

  1. I think i’ve seen this somewhere before…but it’s not bad at all

  2. This effect is excellent!