Channel 9Microsofthttp://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.pngChannel 9https://channel9.msdn.com/Niners/c4f.Andy-Beaulieu/Posts
Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.https://channel9.msdn.com/Niners/c4f.Andy-Beaulieu/Posts
enTue, 31 Mar 2015 22:03:24 GMTTue, 31 Mar 2015 22:03:24 GMTRev92125Creating a Shuffleboard Game using SilverlightIn this walkthrough, we will create a
table shuffleboard style game for Windows Phone 7 using Silverlight. Many bars feature these long wooden table games, in which players slide metal pucks down the length of the table, attempting to get as close as possible to the far end without sliding
off the edge.

Multi-Targeting

Windows Phone 7 uses a version of Silverlight 3 with a few bonus features. Because this version of Silverlight is so close to the Web version of Silverlight 3, we'll take the approach of
Multitargeting a solution for both platforms. To do so, start with a Silverlight 3 (web) application template, and then add in a Windows Phone project with linked files that re-use the Silverlight 3 solution. This allows us to deploy to many different
platforms using the same code base.

Let's get started by creating our Solution in this way.

Creating the Solution and MainPage

In Expression Blend 4, create a new Silverlight Application + Website template named Shuffleboard. Be sure to select “3.0” from the Version dropdown, as this is what is supported by Windows Phone (in a little bit we'll add in the Windows Phone project template
as well).

In the Objects and Timeline Panel, select the main UserControl and set its Width to 480 and its Height to 800. This is the size of a Windows Phone UI in Portrait mode.

Select the LayoutRoot Grid and set its Width to 480 and its Height to 800.

For games, a Canvas layout container is better than a Grid, so let's change the LayoutRoot container type. Right-click LayoutRoot and select Change Layout Type/Canvas.

Since some parts of our UI can appear outside of the game area, we want to add a Clip to this main canvas so that the user does not see these outside elements. Add the following just under the LayoutRoot Canvas:
This XAML is snippet “MainPage Clip” inside snippets.txt.

<Canvas.Clip><RectangleGeometryRect="0,0,480,800"/></Canvas.Clip>

We'll be using some pre-built Behaviors that make it easy to introduce physics into Silverlight using the Farseer Physics Library. Right-click the Silverlight project and select Add Reference. Select the following assemblies, located in the sample download:

Creating the Game User Control

Next we'll create a separate user control that will contain the core game logic. By creating a separate user control, we can easily target different platforms by placing the user control inside different MainPage elements.

Right-click the Shuffleboard Silverlight project and select Add New Item. Select UserControl and name the control “ucMainGame”.

Change the LayoutRoot element from a Grid to a Canvas.

Set the Width to 480 and the Height to 800 for both the UserControl and LayoutRoot Canvas elements.

Set the Background color to Black for the LayoutRoot Canvas.

Build the project by pressing Ctrl+Shift+B.

Back on MainPage, add an instance of ucMainGame to the page by going to the Assets Panel and expanding Controls/All. Drag an instance of ucMainGame to the artboard.

Rename the ucMainGame control to ucMainGame1.

Set the Left and Top properties of ucMainGame1 to 0.

Creating the Table

We'll use a pre-rendered PNG image for the shuffleboard table.

Create a new subfolder in the Silverlight project named “images”.

Add the following JPG image into the new images subfolder, located in the sample download:
\ShuffleBoard\images\shuffleboardTable.jpg

Open the ucMainGame user control.

Insert a new Canvas element named cnvTable, and set the following attributes:

Width = 480

Height = 800

Left = 0

Top = 0

In the Assets Panel, expand the Behaviors category and drag a PhysicsControllerBehavior on the cnvTable. This behavior introduces the core physics simulation into the game. Set the properties of the Physics Contoller as follows (this turns of gravity and
sets some other physics parms):

Inside the cnvTable Canvas, add a second Canvas named cnvTableInner, which will hold the table image. Set the following properties on cnvTableInner:

Width = 360

Height = 1077

Left = 60

Top = -277

Drag the shuffleboardTable.jpg image from the Projects Panel into cnvTableInner. Set the following properties on the image:

Width = 360

Height = 1077

Left = 0

Top = 0

The Objects and Timeline Panel should look like so:

We will need to detect when a puck hits the edge of the table and “falls off.” Let's add in some Rectangle elements and add Physics Behaviors to them.

Add a new Rectangle named rectSensorLeft and size it so that it covers the entire left side of the table. Set the following properties:

Width = 60

Height = 1190

Left = -40

Top = -334

Opacity = 20%

Drag a PhysicsObjectBehavior from the Assets Panel Behaviors onto rectSensorLeft, and then set its IsStatic property to true.

Add three more Rectangles by copying rectSensorLeft, so that they surround the borders of the table:

rectSensorRight

rectSensorTop

rectSensorBottom

Your artboard should look similar to the following:

Now we'll add in the goal Rectangles at the end of the table. These will be used to determine the number of points a puck receives. Draw out three Rectangles that cover the width of the board and are 100 pixels high. Name these rectPoints3, rectPoints2,
and rectPoints1. Set their Stroke to Red and their Fill to No brush.

Add a TextBlock element inside each Rectangle to depict the points. Set the text properties to 3, 2, and 1 so that the artboard looks similar to the following:

We'll also need a Rectangle representing the “slide zone” where players can legally slide a puck (we don't want to allow sliding all of the way down the table!). Add a Rectangle named rectInBounds and position it at the lower end of the table:

Width=360

Height=292

Left = 60

Top = 508

Fill = No Brush

Stroke = Red

Adding the Pucks

For the pucks, we are going to add in an existing control which has the artwork completed.

Right-click the project and select Add Existing Item.

Browse to the following two files in the sample code download:
\ShuffleBoard\ucPuck.xaml
\ShuffleBoard\ucPuck.xaml.cs

Open ucPuck.xaml on the artboard and notice the following in the Objects and Timeline Panel:

There is a Canvas named Puck that has a PhysicsObjectBehavior applied to it. This allows each instance of this Canvas to behave like a Physics Object so it animates with velocity and force and participates in collisions. Note that this Behavior has a large
MomentOfInertia value. This keeps the object from rotating due to torque and collisions. Also note the RestitutionCoefficient, which gives the object some “bounce.”

There is a “cnvInner” Canvas that defines the look of the Puck.

There is a StoryBoard defined, sbLostPuck, which we will execute when the puck “falls off the edge” of the table.

Open the code-behind file, ucPuck.xaml.cs, and note the get / set property for the color of the puck. This will allow us to create both Red and Blue pucks for each player.

Build the project by hitting Ctrl+Shift+F5 and go back to ucMainGame.

From the Assets Panel, expand Controls/All and find the ucPuck control. Drag an instance of this onto the artboard. Name this
bluePuck1.

Copy and paste bluePuck1 twice so that you have three blue pucks. Name the new pucks
bluePuck2 and bluePuck3.

Copy and paste a fourth puck and name it redPuck1. In the Properties Panel, go to the Miscellaneous Category and change the ColorHighlight and ColorMain properties to a Red color:

Copy and Paste redPuck1 two times and rename these new pucks redPuck2 and
redPuck3.

Let's test our table. Find the PhysicsControllerBehavior just under the cnvTable Canvas in the Objects and Timeline Panel and set the MousePickEnabled property to true.

Run the project by clicking F5. Try dragging some pucks around with the mouse.

Adding the Scoreboard

We need a way of tracking players' scores, so let's add in a simple scoreboard for Blue vs. Red.

Right-click the project and select Add Existing Item.

Browse to the following two files in the download:
\ShuffleBoard\ShuffleBoard\ucScoreBoard.xaml
\ShuffleBoard\ShuffleBoard\ucScoreBoard.xaml.cs

Open ucScoreBoard and notice the following:

It has a TextBlock for Red scores and a TextBlock for Blue scores.

In the code-behind, there are setters and getters to set the score.

Build the project by selecting Ctrl+Shift+B.

Switch back to ucMainGame.

Drag an instance of ucScoreBoard from the Assets Panel onto into LayoutRoot.

Name the element ucScoreBoard1, and position it at the top left of the Canvas like so:

Adding a Player Up Display

We'll need a simple control that displays which player's turn it is.

Right-click the Silverlight project and select Add/Existing Item.

Browse to and select the following two files in the sample folder:
\ShuffleBoard\ucPlayerUp.xaml
\ShuffleBoard\ucPlayerUp.xaml.cs

Note the following about ucPlayerUp:

The code-behind file has a simple property, IsBlueTurn, which shows the appropriate message in the UI.

Build the project by clicking Ctrl+Shift+B

Back on ucMainGame, drag an instance of ucPlayerUp into cnvTableInner.

Name the control ucPlayerUp1 , and set the following properties:

Adding a 3D Look

Let's give our table a bit of a 3D look by adding a Perspective transform so the table appears to go off into the distance.

Create a new StoryBoard named sbRotateTable.

Select the cnvTable Canvas element.

Advance the timeline ahead one second.

In the Properties Panel, under Projection, set the X value to -40.

Your artboard should now look something like this:

Close the Storyboard to end recording.

We want to rotate the table after the PhysicsController is initialized so the Physics Helper can determine the boundaries of the physics objects properly. Start by adding in some Using statements at the top of ucMainGame.xaml.cs:
This code is snippet “ucMainGame Imports” inside snippets.txt.

using System.Collections.Generic;
using Spritehand.FarseerHelper;
using FarseerGames.FarseerPhysics.Mathematics;
using System.ComponentModel;

Next, let's add in some class-level declarations, which will store the physics controller, list of pucks, and some variables used to track shooting and scoring:
This code is snippet “ucMainGame Declarations” inside snippets.txt.

In the ucMainGame() constructor, add some code to set the MaxFrameRate to 30 (Windows Phone will be limited to 30 FPS) and wire up the Loaded event handler.
This code is snippet “ucMainGame Constructor” inside snippets.txt.

Next, we'll add in the event handlers that we just wired up in the loaded event. Note that the Initialized event starts the Rotate Table StoryBoard.
This code is “ucMainGame Event Handlers” inside snippets.txt.

Run the Project by clicking F5. Note the 3D look and try manipulating the pucks with the mouse.

Controlling the Pucks

Next, we'll add logic to control the player's turn and control and along with score. Note that, when we implement the Windows Phone version in a bit, we can take advantage of Multitouch Manipulation events. But since these events are not available in the
Web version of Silverlight 3, we'll use a simple mouse input mechanism.

Let's turn off the default mouse manipulation. Select the PhysicsControllerBehavior just under the cnvTable Canvas and set the MousePickEnabled property to false.

We need to get references to our Pucks, which the Physics Helper has translated into PhysicsSprite objects. A Physics Sprite contains the XAML UI for the Physics Object, plus the Physics Engine attributes for the underlying physics objects–including boundary
shape, mass, velocity, etc.
This code is “ucMainGame Initialized” inside snippets.txt.

Now we need to handle the Mouse events on the pucks in order to control the player's shot. When the player clicks the mouse down on a puck, we track the position along with time that they clicked. When the player moves the mouse, we update the puck position
and also check if the player paused or moved backwards. We do this in case the player is just adjusting the puck position and not yet sliding the puck for a shot. Finally, in the Mouse up event, we release the puck in the specified direction and apply an appropriate
amount of force to it. Copy in the snippet “Puck Mouse Control” from snippets.txt. Code is not shown here for brevity.

When the Physics Helper Library does its magic, it translates existing UI Elements into PhysicsSprite objects. So what if we want to get at the original controls, perhaps to execute a StoryBoard that we defined on them? We can do this by using the FindName
method to get the original user control instance. So, add the code below, which we'll use to get a reference to the Puck Storyboard “sbLostPuck”.

Implement the “Game Loop”

Most games are controlled by a “Game Loop” that executes many times per second. Within this Game Loop, we can check for collisions, perform enemy AI, and scoring. The PhysicsController fires an event called “TimerLoop” that we can use for this purpose.

Replace the existing TimerLoop and Collision events with the following code snippet, which checks to see if any pucks have been shot and if we are ready for the next shot. Do this by seeing if the puck velocity has slowed down to nearly a stop…
This code is snippet “Timer Loop” inside snippets.txt.

Targeting Windows Phone

So far, we've created a Silverlight 3, web-based version of a shuffleboard game. Next we'll quickly port this to Windows Phone, taking advantage of some of the platform's capabilities, such as multitouch. We'll do this by using
linked files that point back to our existing Silverlight 3 project.

Right-click the Silverlight solution in Blend and select Add New Project.

Select Windows Phone Application and enter ShuffleBoard.WindowsPhone for the name.

Delete the TitleGrid and ContentGrid elements from the Objects and Timeline Panel.

Convert LayoutRoot to a Canvas by right-clicking it and selecting Change Layout Type/Canvas.

Right-click the project and select Add Reference. Browse to the following assemblies located in the sample download (these are the WindowsPhone versions of the Physics Helper and Farseer):

We need references to the assemblies used for Behaviors. An easy way to do this is to add a Behavior to an element and then delete it. From the Assets panel, drag a PhysicsControllerBehavior onto LayoutRoot and then delete it. Note that this adds a reference
to System.Windows.Interactivity to the project.

Next, we'll add in the linked files from the existing Silverlight 3 project. Right-click the ShuffleBoard.WindowsPhone project and select Add/Link to Existing Item. Select the following files:

ucMainGame.xaml

ucMainGame.xaml.cs

ucPlayerUp.xaml

ucPlayerUp.xaml.cs

ucPuck.xaml

ucPuck.xaml.cs

ucScoreBoard.xaml

ucScoreBoard.xaml.cs

8. Add a new folder to the project named images.

9. Right-click the images folder and select Link to Existing item, then navigate to the following image in the sample folder:
\ShuffleBoard\images\shuffleboardTable.jpg

Build the project by clicking Ctrl+Shift+B.

From the Assets Panel, under Controls/All, find ucMainGame and drag an instance onto LayoutRoot. Set the Left and Top properties to 0.

Right-click the WindowsPhone project and select “Startup” to set this as the startup project.

Run the project by clicking F5.

Windows Phone Touch Input

So far, we've used a simple mouse-event-based input mechanism for shooting the pucks. But on the Windows Phone 7 platform, we can do better than that by using Multitouch events. These events include an inertia property that will make our puck physics more
realistic.

Since we are going to need to support two different platforms now (Web and Windows Phone), we need to introduce a Conditional Compilation Symbol so that the compiler can differentiate between each platform's code.

Open the solution inside Visual Studio by right-clicking it in the Projects Panel and then select “Edit in Visual Studio”

4. Add in a new compilation symbol for WINDOWS_PHONE.
NOTE: Future releases of WP7 Tools will likely define a default compilation symbol, so you may already see one defined here.

Now we'll add in the Windows Phone-specific events for manipulation using touch. Open ucMainGame.xaml.cs and find the _physicsController_Initialized event handler. Replace the events for the mouse events with the following, which will wire up either the
manipulation events (for Windows Phone) or the mouse events (for Silverlight Web):
This code is snippet “Manipulation Events” inside snippets.txt.

Now we just need to implement those event handlers for manipulation. The main consideration here is that the ManipulationCompleted event passes in a FinalVelocity.LinearVelocity parameter, which we can use to create realistic physics from the user's shot:

Performance

Depending on your configuration, you may experience poor performance for the shuffleboard game when running it in the Windows Phone emulator. There are different reasons for this, including video card drivers and virtualization settings. Please refer to
this blog post, which details these performance considerations.

1. Inside the ucMainGame constructor, let's turn on the Frame Rate counter so we can see our current frame rate. This code is snippet “Frame Rate Counter” inside snippets.txt

Application.Current.Host.Settings.EnableFrameRateCounter = true;

Run the project by hitting F5, and note the current frame rate. NOTE: Your development configuration may prevent you from having an adequate framerate in the Windows Phone Emulator! Please refer to
this blog post for tips on emulator performance.

One performance tweak we can easily make is taking advantage of hardware acceleration. Silverlight enables us to use the video card to render elements, which can greatly increase performance. To do this, we add a Cachemode=”BitmapCache” attribute to any
elements we want to hardware accelerate.

Open ucPuck.xaml and note that there is a CacheMode attribute on the Puck Canvas.

Open ucMainGame.xaml and add a CacheMode attribute to the cnvTable Canvas element.

Adding Sound

Sound is one area where Windows Phone and Web Silverlight differ a bit. Under Silverlight for Web, we can use the MediaElement class to play back WMA and MP3 format audio. Multiple instances of the MediaElement class can be played simultaneously, and the
sound output will be automatically mixed.

However, on Windows Phone we have access to the XNA game libraries, including sound support. This is a much more efficient way to add mixed sound to a Silverlight game on Windows Phone, but it only supports WAV format sound files.

The Physics Helper Library has a useful class wrapper for sounds, which we'll use to play a “hit puck” sound on both platforms.

Add an existing item to the sounds folder from this location:
\ShuffleBoard\ShuffleBoard\sounds\hitPuck.wma

Set the Build Action of the file to Content.

In the ShuffleBoard.WindowsPhone project, right-click and select Add Folder.

Name the folder sounds.

Add an existing item to the sounds folder from this location:
\ShuffleBoard.WindowsPhone\sounds\hitPuck.wav

Set the Build Action of the file to Content.

Inside ucMainGame.xaml.cs, add a class-level declaration for a SoundMain class (this is defined in the Physics Helper Library):
This snippet is “Declare the Sound” inside snippets.txt.

SoundMain _soundPuckHit;

10. Inside the ucMainGame_Loaded event, add code to declare the two sounds. Note that Windows Phone uses a WAV format sound without a “/” prefix for the root.
This snippet is “Declare the Sound” inside snippets.txt.

Summary

Since the 1.1 Alpha release, Silverlight has offered a compelling casual game development environment. With the addition of Windows Phone, along with demos of Silverlight running on other embedded devices, you can bet the future of Silverlight for gaming
is bright.

]]>https://channel9.msdn.com/coding4fun/articles/Creating-a-Shuffleboard-Game-using-SilverlightIn this walkthrough, we will create a
table shuffleboard style game for Windows Phone 7 using Silverlight. Many bars feature these long wooden table games, in which players slide metal pucks down the length of the table, attempting to get as close as possible to the far end without sliding
off the edge.
Multi-Targeting
Windows Phone 7 uses a version of Silverlight 3 with a few bonus features. Because this version of Silverlight is so close to the Web version of Silverlight 3, we'll take the approach of
Multitargeting a solution for both platforms. To do so, start with a Silverlight 3 (web) application template, and then add in a Windows Phone project with linked files that re-use the Silverlight 3 solution. This allows us to deploy to many different
platforms using the same code base.
Let's get started by creating our Solution in this way.
Creating the Solution and MainPage
In Expression Blend 4, create a new Silverlight Application &#43; Website template named Shuffleboard. Be sure to select “3.0” from the Version dropdown, as this is what is supported by Windows Phone (in a little bit we'll add in the Windows Phone project template
as well).
In the Objects and Timeline Panel, select the main UserControl and set its Width to 480 and its Height to 800. This is the size of a Windows Phone UI in Portrait mode.
Select the LayoutRoot Grid and set its Width to 480 and its Height to 800. For games, a Canvas layout container is better than a Grid, so let's change the LayoutRoot container type. Right-click LayoutRoot and select Change Layout Type/Canvas.
Since some parts of our UI can appear outside of the game area, we want to add a Clip to this main canvas so that the user does not see these outside elements. Add the following just under the LayoutRoot Canvas:
This XAML is snippet “MainPage Clip” inside snippets.txt.
&lt;Canvas.Clip&gt;
&lt;RectangleGeometry Rect=&quot;0,0,480,800&quot;/&gt;
&lt;/Canvas.Clip&gt;
We'll be using some pre-built Behaviorhttps://channel9.msdn.com/coding4fun/articles/Creating-a-Shuffleboard-Game-using-Silverlight
Tue, 15 Jun 2010 21:23:23 GMThttps://channel9.msdn.com/coding4fun/articles/Creating-a-Shuffleboard-Game-using-SilverlightAndy Beaulieu Andy Beaulieu 8https://channel9.msdn.com/coding4fun/articles/Creating-a-Shuffleboard-Game-using-Silverlight/RSSExpression BlendGamingMobilePhysicsSilverlightWindows PhoneXAMLCreating a Pinball Game in Silverlight: Using the Physics Helper Library + Farseer PhysicsIn this tutorial, we'll create a Silverlight pinball game using Behaviors,
a new addition to Expression Blend 3 & Silverlight that allows you to create interactivity with little or no coding.

Run install.bat. (Note: this copies a few required assemblies to a folder in Blend 3.)

Getting Started & Making the Ball

Next, you create the controller and the pinball. Here's how.

Open Expression Blend 3 and create a new “Silverlight 3 Application + Website” named PinballGame.

Change your default layout container to a Canvas. You can do this in the Objects and Timeline panel by right-clicking LayoutRoot and selecting Change Layout Type/Canvas. Canvas layout containers are better for games because they allow for positioning of
elements at absolute (x,y) coordinates.

Give the application a bigger default size. Select the UserControl element in the Objects and Timeline panel. Then, in the Properties panel, change the Width to 800 and the Height to 600.

Add a Physics Controller Behavior to our main game Canvas. From the Asset Panel, find the PhysicsController Behavior and drag it to the Objects and Timeline Panel. Then, drop it on the LayoutRoot Canvas.

Change a few of the PhysicsController's properties, to make it easier to use. In the Objects and Timeline Panel, select the PhysicsControllerBehavior assigned to LayoutRoot. Then, set the highlighted properties as follows in the Properties Window:
1.) Decrease the vertical gravity to 250
2.) Increase the iterations to 200. This will help with collision detection in a fast-action game.
3.) Set MousePickEnabled to true. This will allow us to manipulate objects with the mouse during development and testing.

Create a "playing field" for the pinball. To do this, draw out a Rectangle onto the artboard, just off the bottom of the user control bounds. Set the properties of the Rectangle as follows:

To make “rectPlatform” a physics element, we need to add a PhysicsObjectBehavior to it. Find the PhysicsObjectBehavior in the Assets panel and drag/drop it onto rectPlatform on the Artboard.

In the Objects and Timeline Panel, select the PhysicsObjectBehavior belonging to rectPlatform. Then in the Properties Panel, set the IsStatic property to True so that the platform will stay in place.

Next we'll create the ball. Draw out an Ellipse near the very top of the UserControl and set the following properties:
Name: ellBall
Height: 50 Width: 50 Fill: A color of your choosing.

To make the ball a Physics Object, we need to add a PhysicsObjectBehavior to it. From the Asset Library, drag and drop a PhysicsObjectBehavior onto ellBall.

Run the project by clicking F5. The ball should fall and hit the platform. Use the mouse to manipulate the ball.

Making the Flippers

In a pinball game, the Flippers are controlled by the player and are used to move the ball up the playfield. Standard pinball games have one right and one left flipper, but many games have three or more flippers located in various locations on the playfield.
We'll create two user controls to represent the flippers – a right flipper and a left flipper – that way we can easily add as many flippers as we want to our main playfield.

In the Projects Panel, right-click the PinballGame (Silverlight) project and select Add New Item. Select UserControl and name the control LeftFlipper.xaml.

In the Objects and Timeline Panel, right-click LayoutRoot and select Change Layout Type/Canvas. This is required for the Physics Helper to work with nested User Controls.

In the Objects and Timeline Panel, select the UserControl element and set its Width and Height to 200 x 200 pixels in the Properties Panel.

Draw out a Rectangle that is about 200 x 50 pixels big, centered in the user control. Round the corners of the Rectangle.

From the main Blend menu, select Object/Path/Convert to Path. This will create a new Path element from the Rectangle primitive. Then select the Direct Selection tool from the Toolbox, which will allow you to manipulate the individual points on the Path.

Select the top, left two points on the Path and move them down so that you end up with a more “flipper like” shape:

In the Toolbox, select the Selection arrow and rotate the flipper 45 degrees so that it looks similar to this (be sure the flipper is still within the bounds of the user control):

Right-click the flipper Path and select Group Into/Canvas. Name the Canvas
cnvLeftFlipper and resize it so that it surrounds the entire flipper Path. Note that you could “embellish” the cnvLeftFlipper with additional elements if you wish.

Next we'll create a Joint so that the Flipper can rotate on an axis. We'll need something to anchor the joint to, so first let's add a small Static object to hold the Joint in place. Draw out a Rectangle at the upper left of the flipper and name the Rectangle
rectHolder.

To add a Joint, we will need a UI element to visually represent where we want the joint created. You can use any element you want for this, but an Ellipse works pretty well. Draw out an Ellipse on top of the rectHolder.

Now we can add all of the required Physics Behaviors to the User Control.

From the Asset Library, drag a PhysicsObjectBehavior to the rectHolder Rectangle. Set its IsStatic property to True. Since we don't really want to see the rectHolder in our UI, just send it to the back of the elements (Right-click, then select Order/Send
to Back).

Drag a PhysicsObjectBehavior to the cnvLeftFlipper Canvas. Set the RestitutionCoefficent property to “0.1”. (This makes the flipper a bit more “bouncy” on collisions)

Drag a PhysicsJointBehavior to the Ellipse. Set the Body1 property to “cnvLeftFlipper” and the Body2 property to “rectHolder”. Set the CollisionGroup to “1” and the AngleLimitLower and AngleLimitUpper to 0 and 50 respectively. Also enable the AngleSpring:

Drag a PhysicsApplyTorqueBehavior to cnvLeftFlipper. We want to apply Torque when the user presses the Left arrow key, so we'll create a Trigger for this. Select the Behavior and in the Properties Panel, click the New Trigger button.

Select the PhysicsKeyTrigger type from the popup.
Set the Key property for the Trigger to “Left” and the TorqueValue to -100000

Build the Project so that the LeftFlipper user control is available.

Open MainPage.xaml and drag an instance of LeftFlipper from the Asset Library onto the Artboard. Position it near the bottom of the user control and slightly to the Left.

Run the project and try the flipper with the Left arrow key.

In this step, we'll create a copy of “LeftFlipper” to make a “RightFlipper”. In the Projects Panel, right-click LeftFlipper.xaml and select Copy. Then right-click the PinBallGame Project and select Paste.
You now have a new User Control named “Copy of LeftFlipper.xaml”. Rename this to RightFlipper.xaml. Then in the code-behind file, make sure the Class and Constructor are also renamed to “RightFlipper”.
Change to XAML view for RightFlipper.xaml and change the x:Class attribute so that it inherits from RightFlipper:

Open RightFlipper.xaml and find the pathLeftFlipper element. Rename this to pathRightFlipper. Then, rename “cnvLeftFlipper” to “cnvRightFlipper”. Rename “rectHolder” to “rectRightHolder” and position the rectHolder and joint ellipse so that they are in the
correct location for the flipper:
Modify the PhysicsJointBehavior for the joint in the Objects and Timeline Panel. Change BodyOne to “cnvRightFlipper”, BodyTwo to “rectRightHolder” and change the Angle limits so they are appropriate for the opposite flipper:
Select the PhysicsApplyTorqueBehavior for cnvRightFlipper in the Objects and Timeline Panel. Change the Key property for the trigger to “Right” so that it will initiate on the Right Arrow key down. Also change the TorqueValue so that it will apply torque clockwise:

Add an instance of RightFlipper onto the MainPage.xaml and position it to the right of LeftFlipper.

Test the project by clicking F5. You can now click left and right arrows keys to manipulate the paddles.

Creating the Playfield + Scrolling

Now let's create more of a playfield for our Pinball game and add a Camera control so that the game will scroll and always follow the pinball. Feel free to tweak the design as you wish.

Open MainPage.xaml in Expression Blend and zoom out by using Ctrl plus minus (Ctrl -).

Draw out a Path using the Pen tool for the right border. Note that you can extend above the upper bounds of the User Control. Group this into a Canvas named “cnvLeftBorder” (right click the Path and select Group Into/Canvas).

Drag a PhysicsObjectBehavior from the Asset Library onto cnvLeftBorder and set the IsStatic property to True. Also set the CollisionGroup property to “1” so that collisions will not occur between the border and the Flippers.

Repeat Steps 2 and 3 above for the right border, naming that cnvRightBorder. You should have something similar to the following:

Continue adding border controls and applying physics behaviors until you are happy with your playfield. Make the playfield completely closed in so that the ball cannot escape (except by the bottom trap of course!)

You can also add more LeftFlipper and RightFlipper controls so that the player can more easily move the ball up the playfield. Here is one example playfield design:

To enable scrolling, we can add a Camera Controller to the ball, causing the camera to follow the ball around the screen. Drag a PhysicsCameraBehavior from the Asset Library onto the ellBall element.

Creating a Kicking Target

Pinball games have lots of different types of targets – some are simple sensors which give points on contact, others are little toys that gobble up the ball for a few seconds. In this step, we'll create a Kicking Target, which gives points when hit by the
ball but also kicks the ball back in the opposite direction.

Create a new User Control named KickingTarget.

Change the LayoutRoot container to a Canvas by right-clicking and selecting Change Layout Type/Canvas.

Select the [UserControl] in the Objects and Timeline Panel and set its Width and Height to 100 x 100.

Draw out an Ellipse that is 90x90 pixels, and positioned at Left, Top 5,5 (so that it is centered in the control).

Draw out a second Ellipse that is 70x70 pixels and positioned and Left, Top 15, 15.

Group the two Ellipses into a Canvas by selecting them both in the Objects and Timeline Panel and selecting Group Into/Canvas. Name the Canvas “cnvKicker”.

Drag a PhysicsObjectBehavior from the Asset Library onto cnvKicker. Set the IsStatic and RestitutionCoefficient properties as shown below. Setting the RestitutionCoefficient above a value of 1 will make the object “kick” things back.

Build the project so that the new user control is available. Then open MainPage.xaml and add a few instance of “KickingTarget” to the page.

Run the project and try out the Kicking Targets.

Optimizing Performance

Our pinball game is looking up, but the performance could be a lot better. The startup time for the game is taking quite awhile because the Physics Helper Library is determining the outline of all of the shapes. Also, the frame rate is too low.

By default, Silverlight has a target frame rate of 60 frames per second. This is great for a lot of casual games, but Pinball requires a bit more speed. Additionally, Silverlight 3 introduces GPU Acceleration which can greatly increase the performance of
our game by offloading graphics operations to the Video Card.

Open the Default.html page in the website project. This page hosts the Silverlight control and exposes the plugin parameters. Add the following parameters to the plug in to increase the default frame rate and enable GPU Acceleration for our game.

Apply the CacheMode attribute to all elements in the game that are static. Since our pinball game's elements are not animated, we can apply the CacheMode to each of them. (If the objects contained animations within them, then the Cache would
be invalidated during animation).

Now we'll speed up the startup time by adding in a pre-calculated Point Cache. The Physics Helper Library echoes out the calculated points at runtime. Open the project in Visual Studio, and run with debugging on. In the Output Window, Find the ReadBoundaryCache
method that was echoed out and Copy the entire method.

Note that the copied code can contain multiple rows of the same points. You can trim out any rows that are duplicated, for example cnvRightFlipper_1 is a copy of cnvRightFlipper, so you can remove that from the list of points.

In order to load the list of boundary outlines into the Physics Controller, we need to get a reference to the controller through code. Open up MainPage.xaml.cs and add the highlighted code:

Run the project and test the performance. Note that items that have a tint applied to them (Red, Blue, etc.) are NOT being cached and GPU accelerated.

Scoring

In this section, we'll embellish our game with a Score.

We'll create a Canvas that overlays our main Canvas to contain a High Score TextBlock. This is so that the Score TextBlock will not scroll with the rest of the Playfield. Open MainPage.xaml and the select LayoutRoot in the Objects and Timeline Panel. Right-click
LayoutRoot and select Group Into/Canvas.

Add a new StackPanel into this outside Canvas that contains two TextBlock aligned Horizontally. The first TextBlock should contain the Text “Score:” and the second TextBlock should contain the Text “0”. Set the Font Size to a larger value, around 12 pt.
Position the TextBlock at the Top, Left portion of the Canvas.

Next we'll handle the Collision event for the Physics Controller so we can add to the score. Open MainPage.xaml.cs and add in a Property wrapper for the current score:

Adding Sound Effects

We can easily add buffered sound effects using the PhysicsSoundBehavior.

In Visual Studio, Import two sound files into the project, score.wma and click.wma. Set their Build Action to Content.

Open MainPage.xaml in Expression Blend. Drag a PhysicsSoundBehavior to the LayoutRoot Canvas. Set the TriggerType to PhysicsCollisionTrigger and set the following properties:

Drag another PhysicsSoundBehavior to the LayoutRoot Canvas. Set the TriggerType to PhysicsCollisionTrigger and set the following properties:

Drag another PhysicsSoundBehavior to the LayoutRoot Canvas. Set the TriggerType to PhysicsCollisionTrigger and set the following properties:

Run the project.

About the Author

Andy Beaulieu is a software developer and trainer who is well versed in many Microsoft technologies including Silverlight, ASP.NET, ADO.NET and WindowsForms.
Visit Andy's Blog for more fun and games with Silverlight.

]]>https://channel9.msdn.com/coding4fun/articles/Creating-a-Pinball-Game-in-Silverlight-Using-the-Physics-Helper-Library--Farseer-Physics
In this tutorial, we'll create a Silverlight pinball game using Behaviors,
a new addition to Expression Blend 3 &amp; Silverlight that allows you to create interactivity with little or no coding.
Below you'll find a video and step-by-step walkthrough.
Videos:
Part 1
Part 2
Part 3
Part 4
Part 5
Part 6
Part 7a
Part 7b
Part 8
Part 9
Part 10
Setup and Prerequisites
First you have to setup Physics Helper controls into Expression Blend. Follow these steps:
Download the Physics Helper ZIP file from
http://physicshelper.codeplex.com/Release/ProjectReleases.aspx Extract the ZIP file contents and dump them into a folder. Run install.bat. (Note: this copies a few required assemblies to a folder in Blend 3.)
Getting Started &amp; Making the Ball
Next, you create the controller and the pinball. Here's how.
Open Expression Blend 3 and create a new “Silverlight 3 Application &#43; Website” named PinballGame.
Change your default layout container to a Canvas. You can do this in the Objects and Timeline panel by right-clicking LayoutRoot and selecting Change Layout Type/Canvas. Canvas layout containers are better for games because they allow for positioning of
elements at absolute (x,y) coordinates.
Give the application a bigger default size. Select the UserControl element in the Objects and Timeline panel. Then, in the Properties panel, change the Width to 800 and the Height to 600.
Add a Physics Controller Behavior to our main game Canvas. From the Asset Panel, find the PhysicsController Behavior and drag it to the Objects and Timeline Panel. Then, drop it on the LayoutRoot Canvas.
Change a few of the PhysicsController's properties, to make it easier to use. In the Objects and Timeline Panel, select the PhysicsControllerBehavior assigned to LayoutRoot. Then, set the highlighted properties as follows in the Properties Window:
1.) Decrease the vertical gravity to 250
2.) Increase the iterations to 200. This will help with collision detection in a fast-achttps://channel9.msdn.com/coding4fun/articles/Creating-a-Pinball-Game-in-Silverlight-Using-the-Physics-Helper-Library--Farseer-Physics
Mon, 30 Nov 2009 19:20:00 GMThttps://channel9.msdn.com/coding4fun/articles/Creating-a-Pinball-Game-in-Silverlight-Using-the-Physics-Helper-Library--Farseer-PhysicsAndy Beaulieu Andy Beaulieu 11https://channel9.msdn.com/coding4fun/articles/Creating-a-Pinball-Game-in-Silverlight-Using-the-Physics-Helper-Library--Farseer-Physics/RSSGamingSilverlight