XNA Game Studio for Fun, Profit, Danger, Excitement and Windows Phone 7 Games
Rob Miles MVPLecturerThe University of Hull, UK
Agenda
Quick phone overviewGetting started writing an XNA gameAdding touch and gesture inputUsing the accelerometerGetting rich in the MarketplaceIn game advertisingWhat to do next
THE WINDOWS PHONE HARDWARE
Display480x800 QVGA320x480 HVGA
Capacitive touch4 or more contact points
Camera5 mega pixels or moreDedicated camera button
Hardware buttonsStart, Search, Back
SensorsA-GPS, Accelerometer, Compass
GPUDirectX 9 acceleration
CPUARMv7 Cortex/Scorpion or better1G
Memory256MB RAM or more8GB Flash or more
MultimediaCommon detailed specsCodec acceleration
WINDOWS PHONE AS AN XNA PLATFORM
Windows Phone is a great platform for gamesPerformance is impressive, especially in 3D
Hardware based graphics accelerationThere are some very interesting input optionsYou can use all the hardware and sensors in your Windows Phone gamesPotential for Xbox Live integration
Support for Avatars and AchievementsSupport for in-game advertising
Viable alternative to charging for your code
QUICK OVERVIEW OF XNA
The XNA Framework provides everything you need to get started writing games:Full Content Management (integrated into Visual Studio)Support for 2D Sprite-based gameplay Support for 3D gamesCommon behaviours across the Windows PC, Xbox 360 and Windows Phone
One game engine can run on all platformsWell factored object model
HOW GAMES WORK
Every game that has ever been written has these fundamental behaviours:Initialise all the resources at the start
fetch all textures, models, scripts etcRepeatedly run the game loop:
Update the game worldread the controllers, update the state and position of game elements
Draw the game worldrender the game elements on the viewing device
METHODS IN AN XNA GAME
The XNA Game class contains methods that will provide these behavioursInitialise all the resources at the start
The Initialize and LoadContent methodsRepeatedly run the game loop:
Update the game worldThe Update method
Draw the game worldThe Draw method
GETTING STARTED WITH XNA
When you create a new XNA game project you are provided with empty versions of the game methodsCreating an XNA game is a matter of filling in these methods to get the game behaviours that are requiredWe are going to start by getting some clouds moving around the displayThen we are going to add some complication and see where it gets us
Cloud and Games
Apparently the future of computing is “in the cloud”Perhaps the future of games is tooWe can start with a drawing of a cloud and see where this takes usFor me this is the fun of making games
Creating a Game World// Game WorldTexture2D cloudTexture;Vector2 cloudPosition;
A game needs a “Game World” which holds all the objects in the gameLoadContent will put content into themUpdate will update their state Draw will draw them
To start with our game just contains a cloud texture and position
Loading the Cloud Textureprotected override void LoadContent(){ spriteBatch = new SpriteBatch(GraphicsDevice);
cloudPosition = new Vector2(0, 0); cloudTexture = Content.Load<Texture2D>("Cloud");}
This code loads our cloud textureIt also sets the draw position for the cloudIt also makes a SpriteBatch, which is used by XNA to batch up drawing operations
Drawing the Cloud Textureprotected override void Draw(GameTime gameTime){ GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(); spriteBatch.Draw(cloudTexture, cloudPosition, Color.White); spriteBatch.End();
base.Draw(gameTime);}
This code uses the spriteBatch to draw our cloudIt also draws a blue sky as a background
1: Simple Cloud
Rob MilesUniversity of Hull
demo
Orientation in XNA Games
The default orientation is landscapeThe game will adjust for either way round
If the phone is tipped into portrait orientation the display will not be adjustedYou can select portrait orientation or allow the game to be played in multiple orientations
graphics.SupportedOrientations = DisplayOrientation.Portrait | DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
Orientation Events and Status
Games can bind to the OrientationChanged event to get notifications of when the phone orientation changes
Window.OrientationChanged += new EventHandler<EventArgs>(Window_OrientationChanged);...void Window_OrientationChanged(object sender, EventArgs e){ if (Window.CurrentOrientation == DisplayOrientation.Portrait) { // gone to portrait orientation }}
Orientation and the Accelerometer
If you use the accelerometer in your games you will find that it always provides values in the same frame of reference
This is as if the phone was being used in Portrait modeIf you allow multiple orientations your code must allow for thisI tend to force the game into just the one orientation
Screen Size in XNA Gamesgraphics.PreferredBackBufferWidth = 240;graphics.PreferredBackBufferHeight = 400;
The default Windows Phone display size is 800x480 pixelsIf you specify other resolutions the display is automatically scaled to reflect this
The hardware will introduce “letterbox” bands if requiredChanging the size of the screen is a good way to get a performance boostAt the moment our cloud is being drawn in the original texture size (200x100 pixels)
We can scale the drawing if we wish
Hiding the Status Bar
graphics.IsFullScreen = true;
The status bar gives notifications to the phone userIt is particularly obvious if a light background is selected
You can disable it by requesting a full screen display
Selecting Initial Preferencesprotected override void Initialize(){ graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft ; graphics.IsFullScreen = true; graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 480;}
XNA provides an Initialize method to select preferencesThis is called once when a game starts running
Drifting our CloudVector2 cloudSpeed = new Vector2(1.5f, 0);
protected override void Update(GameTime gameTime){ cloudPosition += cloudSpeed;
base.Update(gameTime);}
The Update method is called 30 times a secondThis is half the rate of XNA on Xbox or Windows PC
We can use it to drift the cloud across the screen
2: Drifting Cloud
Rob MilesUniversity of Hull
demo
Creating Game Componentsinterface ISprite{ void Draw(CloudGame game); void Update(CloudGame game);}
// Game WorldList<ISprite> gameSprites = new List<ISprite>();
We really need more than one cloudWe can make a ISprite component which has Draw and Update behavioursWe can then make a list of these to use in our game
The Cloud Classclass Cloud : CloudGame.ISprite{ public Texture2D CloudTexture; public Vector2 CloudPosition; public Vector2 CloudSpeed;
public void Draw(CloudGame game) ...
public void Update(CloudGame game) ... public Cloud(Texture2D inTexture, Vector2 inPosition, Vector2 inSpeed) ...}
Making Random CloudsVector2 position = new Vector2(rand.Next(GraphicsDevice.Viewport.Width), rand.Next(GraphicsDevice.Viewport.Height));
Vector2 speed = new Vector2(rand.Next(0, 100) / 100f, 0);
Cloud c = new Cloud( cloudTexture, position, speed);
gameSprites.Add(c);The Cloud class has a constructor that takes a texture, position and speed and creates a Cloud instanceThis is then added to the sprites for this game
Updating Spritesprotected override void Update(GameTime gameTime){ foreach (ISprite sprite in gameSprites) sprite.Update(this);
base.Update(gameTime);}
The Update behaviour works through each game component and updates itThe component is given a reference to the game so that it can affect the game state if required (e.g. update the score)There is a similar loop for Draw
3: Drifting Clouds
Rob MilesUniversity of Hull
demo
Cloud Bursting Game
We could add a simple game mechanic so that players can burst the clouds by touching themTo do this our game must detect touch events from the phone touch panelThis is very easy to doThe phone can detect and track up to 4 touch events Each cloud can check during its Update method to see if it has been burst
Getting Touch LocationsTouchCollection Touches;
protected override void Update(GameTime gameTime){ Touches = TouchPanel.GetState();
foreach (ISprite sprite in gameSprites) sprite.Update(this);}
The Touch Panel provides a method called GetState that supplies a collection of TouchLocation values that describe the current touch status
Using Touch Locationsforeach (TouchLocation touch in game.Touches){ if (touch.State == TouchLocationState.Pressed) { if ( CloudContains(touch.Position) ) { CloudPopSound.Play(); Burst = true; return; } }}
A program can get the status and location of the touch event and then burst the cloud that contains that location
Cloud Contains methodpublic bool CloudContains(Vector2 pos){ if (pos.X < CloudPosition.X) return false; if (pos.X > (CloudPosition.X + CloudTexture.Width)) return false; if (pos.Y < CloudPosition.Y) return false; if (pos.Y > (CloudPosition.Y + CloudTexture.Height)) return false; return true;} This method returns true if the cloud region
contains a particular point
Pop Sound Effectpublic SoundEffect CloudPopSound;...SoundEffect CloudPopSound = Content.Load<SoundEffect>("Pop");...CloudPopSound.Play();Sound effects are loaded from WAV files which are added as content alongside image texturesWe can then play them on demandThe Windows Phone supports at least 64 simultaneous sound voicesWe can adjust pitch, location and volume of effects
4: Bursting Clouds
Rob MilesUniversity of Hull
demo
Touch States
An active touch location can occupy one of a number of states:
TouchState.PressedTouchState.MovedTouchState.Released
Each touch location also has a unique ID so that it can be identified throughout its lifecycleThis gives very good control of touch events at a very low level
Flicking Clouds using Gestures
The touch panel also provides gesture supportWe can use the gestures to allow the player to flick clouds around the skyThe game program can register an interest in gesture eventsThese are then tracked and buffered by the touch panelEach gesture gives a particular set of information
Registering for a Gesture TouchPanel.EnabledGestures = GestureType.Flick;
The Flick gesture lets a game detect the direction and speed of a flick on the phone screenThere are other gesture types:
Tap DoubleTapHoldVerticalDragHorizontalDragFlickPinch
Using a Gesturewhile (TouchPanel.IsGestureAvailable){ GestureSample gesture = TouchPanel.ReadGesture();
if (gesture.GestureType == GestureType.Flick) { waterCloud.CloudSpeed = gesture.Delta / 100f; }}
This code uses the Delta value of the flick gesture to allow players to flick the cloud towards the plant and water it
5: Flicking Clouds
Rob MilesUniversity of Hull
demo
Using the Accelerometer
You can also use the accelerometer to control the behaviour of objects in your gameThe Accelerometer can measure acceleration in X, Y and ZYou can use just the X and Y values to turn it into a replacement for a gamepadThe values that are returned are in the same range
-1 to +1 in each axisA value of 1 means 1G (G is the acceleration due to gravity)
Adding the Sensors Library
The reason why the accelerometer is event driven is that XNA actually uses the same sensor interface as SilverlightThis means that you need to include the appropriate sensor library into your program to obtain accelerometer readingsYou need to add Microsoft.Devices.Sensors to your solution to bring in the library
Adding the Sensors Namespace
using Microsoft.Devices.Sensors;
Once you have added the library you can use the Sensors objectsAdding the namespace to your program makes the code a bit cleanerNote that you only have to do this for the accelerometer
Accelerometer Events
Unlike other XNA input devices the accelerometer in XNA 4.0 is event drivenThe accelerometer generates events when new readings are availableYou must bind a method to the eventThe method can store the settings for later use The code in an Update method can read the settings and use them to update the position of game objects
Starting the AccelerometerAccelerometer accel;private void startAccelerometer(){ accel = new Accelerometer();
accel.ReadingChanged += new EventHandler <AccelerometerReadingEventArgs> (accel_ReadingChanged); accel.Start();}
This creates an accelerometer, binds the reading changed event and starts it running
Accelerometer Event HandlerVector3 accelReading;void accel_ReadingChanged(object sender, AccelerometerReadingEventArgs e){ lock (this) { accelReading.X = (float)e.X; accelReading.Y = (float)e.Y; accelReading.Z = (float)e.Z; }}
When we get a new reading we copy this into a vectorWe use a lock so that this process is never interrupted
Reading the Accelerometer Vector3 getAccReading(){ Vector3 result;
lock (this) { result = new Vector3(accelReading.X, accelReading.Y, accelReading.Z); } return result;}
This method returns the most up to date reading
Acceleration and PhysicsVector3 acceleration = game.getAccReading();
CloudSpeed.X -= acceleration.Y * 0.1f;
CloudPosition += CloudSpeed;
This is a very simple physics modelThe tipping of the phone controls the acceleration of the clouds in the X direction
Note we have to use the Y value of the acceleration as the accelerometer readings are relative to portrait mode
6: Tipping Clouds
Rob MilesUniversity of Hull
demo
Falling through Clouds
XNA can scale textures and draw them transparentlyThis means that we can get some rather nice graphical effectsI wanted to get a “skydiver” effect of falling through clouds towards the groundI thought this might be the basis of a gameThen of course I needed some ground to fall towardsXNA games on the Windows Phone can get this from Bing Maps
Loading Textures from the Webvoid wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e){ if (e.Error == null) { mapImage = Texture2D.FromStream(graphics.GraphicsDevice, e.Result); }}
This is the code that sets the background texture to the image received from Bing MapsYou can use it to take any texture and use it in a game
7: Cloud Landings
Rob MilesUniversity of Hull
demo
Games and Applications
Programs are loaded onto the phone from the Marketplace over the air (WiFi or 3G) or via the Zune applicationThis is the only way to put programs on a “locked” deviceRegistered developers can unlock a device for testing
Joining the Marketplace
If you want to take your games to market you will need to join the Windows Phone Marketplace as a developer
This is managed via your Windows Live identityIt costs $99 per yearStudents can get free membership via DreamSpark
Joining the Marketplace lets you publish games and unlock Windows Phone devices for testing
Developers can unlock up to three devicesStudents can unlock just one
Free and Trial Applications
You can give away up to 100 applications each year you are member of the Marketplace
Any further free applications will cost $20 each for validation
You can also make available “trial” versions of a game or applicationCustomers can purchase an upgrade from within the application
Submitting Applications
You are guided through the submission process for your applicationThe application itself is submitted as a single “xap” fileThis is an archive with a manifest which is generated by Visual Studio when the game is builtIt contains all the game content and resources
Application Approval
The application process is “semi-automatic”Checks for application pre-requisites and code behaviours along with a review of the program itself
Each developer has a dashboard that keeps them informed of the progress of each submission
You can submit upgrades at no costThe submission guidelines give a lot of help to ensure that your submissions have the best chance of succeedingYou must read these before sending a game for approval
Making Money
Marketplace publishers get 70% of the price paid for the gamesThis is paid once you have earned at least $200If you are not from the US you will have to fill in a US Tax Waiver form and fax it to the Windows Marketplace teamYou can still submit applications for sale before you have sorted this out
Adding Advertisements to Games Very easy to incorporate ads into XNA games
Download the Ad-Control SDKAdManager added as a game component – easy to retro-fit to an existing game
Players can click through an advertisement to a web site or call the advertiser from within your game
Advertisements are specifically targeted at each player demographic
You get 70% of the revenue
Microsoft pubCenter
Sign up here so that you can incorporate ads in your games
http://pubcenter.microsoft.com
Find out more about Windows Phone Advertisinghttp://advertising.microsoft.com/mobile-apps
WHAT TO DO NEXT
Download the developer tools from http://create.msdn.comRegister as a developerSign up for Advertisinghttp://pubcenter.microsoft.com Download the sample code from: http://robmiles.com Buy my book Ask Questions….
© 2011 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION
IN THIS PRESENTATION.
Top Related