Some Simple Silverlight 2.0 Particles, with sticky tape ….

image

Live demo here.

There are a few demos of using the HTML Canvas element floating around the web (which exists natively in WebKit, Firefox, and Opera and as a custom class using excanvas for Internet Explorer). I was inspired to clone the particle demo using Silverlight (and add a silly sticky tape feature).

My implementation went a bit overboard so the amount of code I wrote exceeds the original HTML+canvas implementation by several times. Those who like fields and types declared explicitly won’t mind the extra code length — those who are into dynamic languages and everything being declared on the fly won’t (as much). :)

I used the Clip property of the Canvas to restrain any errant particles from leaving their host and a DispatchTimer to update the user interface.

RectangleGeometry clipper = new RectangleGeometry();
clipper.Rect = new Rect(0, 0, this.Width, this.Height);
LayoutRoot.Clip = clipper;

DispatcherTimer tmr = new DispatcherTimer();
tmr.Interval = TimeSpan.FromMilliseconds(10);
tmr.Tick += new EventHandler(UpdateParticles);
tmr.Start();

The DispatchTimer becomes the “game loop”, and every 10 milliseconds moves the particles to their new position.

I couldn’t find a way to get the current mouse position, so I tracked the mouse position manually. If anyone knows of a method equivalent to Mouse.GetPosition in Silverlight, please leave a comment!

The “Random” number generator burned me a few times when I created instances of the Random class and found that most of the particles all had the same starting position and vectors. The Random class in Silverlight uses the TickCount property of the Environment object to seed the Random number generator. By creating a bunch of instances nearly instantly, each was seeded with the same number — which means that the “random” number generator was generating the same numbers for each particle! My fix was to create a static instance of the Random class and reuse that over the lifetime of the Particle classes. Simple fix — and one of those “duh” moments.

Source code.

One Comment

Comments are closed.