March 25th, 2009

Controlling an object using the Keydown function in Silverlight

All Silverlight Examples, Silverlight 2 tutorials, Silverlight C# Tutorials, Silverllight Games, by Gavin Wignall.

The below example shows an object being controlled by user input on a keyboard. I capture the ‘Keydown‘ event and then check what keys are being pressed using a range of ‘if‘ statements.

Upon recognition of a key assigned to a direction, an increase (or decrease depending on direction) is made to a variable that is then applied to the the Helicopters ‘Canvas.setTop‘ or ‘Canvas.setLeft‘.

This movement is then applied every frame using the ‘CompositionTarget.Rendering‘ event.

The ‘Space bar’ or Numeric ’5′ key will level the Helicopter out and stop it moving in any direction. This is done by reducing or increasing the movement in all directions until all values equal zero.

I constantly repeat 2 storyboards to animate the helicopter blades and make visible/collapse one of 5 graphics to display the helicopter facing in the relevant direction that it is moving in. Finally I constantly run a calculation to tilt (RotateTransform) the helicopter in the direction it is moving and making it level when not moving.

To save the user from loosing sight of the helicopter in the above example I have put in a collision check to make sure the helicopter can not fly outside of the viewable area. If the user controls the helicopter to fly past any boundary then the helicopters movement in that direction will be reset to zero.

Next steps

I would like to add a winch that can be dropped down below the helicopter. The winch could then be made to pick objects up and drop them on command.

Get the code

Feel free to grab the code here and start playing!

Back Top

Responses to “Controlling an object using the Keydown function in Silverlight”

  1. Hi, fantastic game your have.

    I am trying to get the keydown to event to fire in silverlight 2, using VB but have no luck. I was using:

    AddHandler KeyDown, AddressOf page_keydown

    but this does not work.

    in c# I can use KeyEventHandler and RoutedEventHandler, but whats the equivalent in VB?.


  2. Dr Gavinda,

    Enjoyed the apps you have Dev’d on here. I can see that inner Developer trying to break free…. ( )

    Keep doing it.


    Ricardos Hillious at March 30, 2009 3:13 pm
  3. Reminds me of Bumble Beegger. The 3/4 view animation is simple yet brilliant, nice plus. Have you tried adding physics to it? (Farseer Physics Engine). I’m linking to this post from the Useful Resources section on

  4. Thanks
    Great code example for us trying to get into Silverlight game programming.

Leave a Reply

Back Top