Adding Thrust
Full source for this tutorial: http://silverlightrocks.com/community/files/folders/slg101_tutorials/entry41.aspx
A famous April Fools Day network RFC stated:
With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is hard to be sure where they are going to land, and it could be dangerous sitting under them as they fly overhead.
Fortunately, we're not dealing with pigs, we're dealing with space ships, although a DreamBuildPlay contest warmup entry replaced space ships with space cows http://udderassault.whatsupnow.com/ so I guess you could make this game with space pigs, but I digress.
So what do we need to do to make the ship move around the screen?
- We need to store the current velocity and current position of the ship somewhere
- When the "up" key is pressed, we need to change the velocity based on the direction the ship is currently pointing, and compare this new value against the maximum velocity of the ship and adjust it appropriately if it exceeds the max velocity
- Based on the velocity, we need to reposition the ship in the game loop
- If the ship hits an edge, we need to "wrap" to the other end of the screen by repositioning the ship
During my previous work with game frameworks, the data type that was used more than any other was the Vector. Unfortunately, the Vector value type is available in WPF, but is omitted in Silverlight 1.1 Alpha. Because I feel it is important to have access to Vector in game programming, I have implemented my own version of the Vector struct in SLG101Utilities. It follows the interface of the WPF version, so if it becomes available, it should be easy to switch.
Vectors are made up of a direction and a magnitude, and in games programming, are most commonly represented as an X and Y value. A vector with a magnitude of 3 in the X direction and 1 in the Y direction can be written as (3,1). We will be using Vectors to store the velocities of our sprites in this game.
Repositioning a Sprite
It may seem strange at first that the User Interface elements in Silverlight don't have a Left or Top property. The explanation that I have heard for this is that Canvases (and other Xaml graphics elements) are not always absolutely positioned, many times they are in a "flow" layout, where there is no absolute positioning, it is all relative to the container and other elements within that container. For this reason, the absolute positioning properties are not built in to the object, and must be accessed indirectly through the SetValue and GetValue methods.
So to set the Left position of an element, you do something like the following:
this.SetValue<double>(Canvas.LeftProperty, 100);
Since this is a bit verbose, let's encapsulate this logic in a Property. Position and Velocity are going to be needed for each sprite in our game, so it makes sense to create a class which our other sprites can inherit from so that we don't have to duplicate this logic. So let's create a class called Sprite. This is the code:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightGames101.Utilities;
namespace SpaceRocks
{
public class Sprite : Control
{
Point position;
public Vector Velocity;
public Point Position
{
set
{
position = value;
this.SetValue<double>(Canvas.LeftProperty, value.X - Width/2);
this.SetValue<double>(Canvas.TopProperty, value.Y - Height/2);
}
get
{
return position;
}
}
}
}
Notice that when setting the position, we subtract half the length and half the width. This is so that Position actually corresponds to the center of the object. This is a matter of preference and also depends on the type of game. In this case, I felt it made sense to center the objects around their position values. If the X and Y values were set without this offset, the position of the sprite would correspond to the top left corner.
Now change the Ship class to inherit from Sprite instead of Control, and add a statement to the end of the Page_Loaded method in the Page class setting the initial position of the ship to the center of the screen or (320,240).
ship.Position = new Point(320, 240);
Now to add code to change the position of the ship. First, if we're thrusting, we need to modify the velocity of the ship based on the ship's current rotation. Let's add a method to the Ship class called Thrust, and a couple of helper methods:
private double DegreesToRadians(double degrees)
{
double radians = ((degrees / 360) * 2 * Math.PI);
return radians;
}
public Vector CreateVectorFromAngle(double angleInDegrees, double length)
{
double x = Math.Sin(DegreesToRadians(180 - angleInDegrees)) * length;
double y = Math.Cos(DegreesToRadians(180 - angleInDegrees)) * length;
return new Vector(x, y);
}
public void Thrust(TimeSpan ElapsedTime)
{
Vector v = CreateVectorFromAngle(RotationAngle, ElapsedTime.TotalSeconds * 300);
Velocity += v;
if (Velocity.Length > 500)
{
Velocity *= (500 / Velocity.Length);
}
}
So what does this do? It converts the current rotation and a magnitude to a Vector. This Vector is in the direction that the ship is currently facing. Then we add that to the current velocity. Then, if the magnitude (Length) of the Velocity is greater than a maximum Velocity of 500, we scale the Velocity vector to have a magnitude of 500.
Now, we need code to call the Thrust method if a certain key is pressed. We'll use the "W" key. So in the GameLoop_Update method in the Page class, add the following:
if (keyHandler.IsKeyPressed(Key.W))
{
ship.Thrust(ElapsedTime);
}
Now all we need to do is to update the position based on the velocity for the sprite in the game loop. We also need to see if the sprite has gone off the screen, and if so, we need to wrap it to the other edge of the screen. Add the following to the Sprite class:
Point WrapPositionToScreen(Point p)
{
Point result = p;
if (result.X > 640) result -= new Vector(640, 0);
if (result.X < 0) result += new Vector(640, 0);
if (result.Y > 480) result -= new Vector(0, 480);
if (result.Y < 0) result += new Vector(0, 480);
return result;
}
public void Update(TimeSpan ElapsedTime)
{
Position = WrapPositionToScreen(Position + Velocity * ElapsedTime.TotalSeconds);
}
And then in the GameLoop_Update method of the Page class, call this update method for the ship object:
ship.Update(ElapsedTime);
and we're done for now. Run the program again and you should be able to maneuver the ship.