Working with physics in Silverlight

I’ve created a Silverlight application that makes a ball bouncing against the borders of a canvas using gravity and friction.  This is how it works:

Step1: create the user interface
I’ve created a new Silverlight project with Visual Studio 2010 and changed the root element of Page.xaml to Canvas.  After that I’ve created a usercontrol named Ball that contains an image and a storyboard.  The storyboard will be used as a timer.

ball.xaml

 

 

 

Step2:  create a new Ball instance
After the main page is loaded I’ve created a new instance of the Ball class and added it to the surface on a certain position.

Step3: writing code for the bounce
I first created some global properties in the Ball class like xSpeed, ySpeed, gravity and friction.  These properties will be set in the constructor.  I also start the storyboard in this constructor.  The duration of this storyboard is 0.03 seconds.  So, the completed event will be executed about 30 times per second.  In the completed event, the current x and y position of the ball are increased with the xSpeed and ySpeed.  There is also a check if the ball collides with a border.  Finally I multiply the xSpeed and ySpeed with the friction and add the gravity to the ySpeed.  After this, the storyboard is restarted.

Step 4: add drag & drop 
In the last step I added drag & drop functionality.  First listen to the MouseLefButtonDown event and start the capture of the mouse.  In the MouseMove event the ball is moved to the position of the mouse and I calculate a new xSpeed and ySpeed which is depending on how fast you move the mouse.  In the MouseLeftButtonUp event I release the capture of the mouse and restart the storyboard so the ball can start bouncing again.

screenshot

 

 

 

 

 

You can download the sample code from here.  Enjoy!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: