App Hub
Banner of Game Development Tutorial

creating a player

Create our very first object and draw it on the screen.

 

We have a blank project, with art assets at the ready. What's the first thing to do? Draw a player character on the screen. We can build everything from there.

Typically, games will represent a particular kind of object - like a player character - with a class; a set of related code that is referenced in a uniform way and can be passed around from function to function in a single unit. Let's make one of those.

Add a new class to your project by pressing SHIFT + ALT + C, and typing in the name Player.cs. Press ENTER.

A brand new code file will open up. This file will contain all the code we'll write to define the player class; all the data and functions that describe what a "player" is to our game. We'll start with basic values such as position, and add a few functions we can call continuously to draw the player on the screen and move them around later.

Inside player.cs

Look at the first few lines of your new code file. There's some code already written for you. You need to make a few changes. Put in the code below, including the using statements, so that your code now looks like this:

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Shooter
{
class Player
{
public void Initialize()
{
}

public void Update()
{
}

public void Draw()
{
}
}
}

Those three items inside the { } marks - Initialize(), Update(), and Draw() - are methods, also known as functions. A method is a set of code instructions that, when called by another method, runs its instructions from top to bottom. You see how the methods have their own { } marks - the code that the method will run will go inside those marks. There's nothing in them yet. We'll fix that soon.

First, we need to add some data - more specifically, some variables that can store data. Think of a variable as a piece of data that can be modified by methods. Sometimes the data is a number, other times it's a long string of text, and other times it's even more complex data like graphics.

We need to add a variety of data that is going to matter to our player, such as where they are on the screen, what their graphic looks like, and so on.

Look for the first { mark under class Player, and enter the following lines:

// Animation representing the player
public Texture2D PlayerTexture;

// Position of the Player relative to the upper left side of the screen
public Vector2 Position;

// State of the player
public bool Active;

// Amount of hit points that player has
public int Health;

// Get the width of the player ship
public int Width
{
get { return PlayerTexture.Width; }
}

// Get the height of the player ship
public int Height
{
get { return PlayerTexture.Height; }
}

Did you notice that we snuck a couple of methods in there? Values that have get and set methods like the above are called properties, and are a way to control how variables get changed or accessed.

There are a number of different types of variables we're using at the moment - you'll see these types quite a bit:

  • int - an integer; this is a whole number like 0, 1, or 42.
  • bool - a boolean; this is a flag that can either be true or false.
  • Vector2 - a two-dimensional vector; it has an X number and a Y number that can be set independently of one another.
  • Texture2D - a two-dimensional graphic; this is a special data type that holds graphical data and can be drawn on the screen.

These data types will work together to draw our player. When we draw the player character, we'll draw a Texture2D at a given Vector2. We'll use more combinations of data to do things like judge how much health the player has, determine when objects collide with one another, and play sounds. For now, we just need to get the player on the screen!

What we need to do is create a method that will set our player's position and initial graphic to the right settings. We'll set a few more values in this method that we'll use later. The Initialize method inside our Player class will work well. We just need to make some changes to it.

Replace the Initialize() method inside the Player class (including the { } marks) with the following code:

public void Initialize(Texture2D texture, Vector2 position)
{
PlayerTexture = texture;

// Set the starting position of the player around the middle of the screen and to the back
Position = position;

// Set the player to be active
Active = true;

// Set the player health
Health = 100;
}

You'll notice a few things we're doing differently:

  • The items inside the ( ) marks are parameters to the method. When you call a method, parameters are objects that you want the method to work with or change.
  • The = sign is an assignment operator - it's instructing the method to set the value of the variable on the left of the equals sign to the value of the variable on the right of the equals sign.
  • Position = position; this is an assignment operator that's setting the Position value in the class to the position value that's in the parameters list. Notice that it's case-sensitive.

Why did we have to pass in "position" as a parameter but not "Position"? This is because Position is a value that belongs to the class. A class can read or write to its own values without using parameters.

We've set the values we need. Now we're going to combine them - the position and the graphic (Texture2D) - to draw the player's graphic on the screen!

The last step to draw the sprite is to queue Texture for rendering. We’ll do this by passing our texture to SpriteBatch within the Draw method.

Replace the Draw() method inside the Player class (including the { } marks) with the following code:

public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(PlayerTexture, Position, null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
}

What's all this? We're doing a few new things.

  • The first thing to notice - we're calling a method, on a parameter. SpriteBatch is a class, just like Player is a class. It has methods and data. SpriteBatch.Draw() is a method.
  • SpriteBatch.Draw() takes a whole lot of parameters. When you call a method, you must pass in all the parameters it asks for. SpriteBatch.Draw() wants a Texture2D, a Vector2, (which we have stored in our Player class as PlayerTexture and Position), and a whole lot of other arguments.
  • Don't worry about the other arguments for now - if at any time you want to know what they are, click on them in the code in Visual Studio, and hit CTRL+SHIFT to see a tooltip that explains the parameter the method is looking for.

We're done with Player.cs for now. We have defined what a "Player" is by creating a class that has all the data and methods we care about. What we need to do now is create one of these Player objects - this is called instantiation, and we're going to do that inside the Game1.cs file.

Switch over to Game1.cs by double-clicking "Game1.cs" in the Solution Explorer.

Inside Game1.cs

Game1.cs is a very important code file - it's already partially filled out, as you'll see. This code is our game loop, and is described by the video at the start of this step.

We're going to be making some additions to this file to make the Player class we've created part of the game loop. When we do this, it will then start to draw on the screen, every frame.

Start at the top of the code, find the string marked public class Game1 : Microsoft.Xna.Framework.Game. A few lines down, below SpriteBatch spriteBatch, add these lines:

// Represents the player
Player player;

What we've just done here is created an instance of the player class you've built. An instance of a class is called an object. Now, you can pass this Player object around to different methods.

Before we use it anywhere, however, we need to initialize the object.

Look down the code, find the method called protected override void Initialize(). Inside that method, add these lines:

// Initialize the player class
player = new Player();

We're using the assignment operator to set our object equal to something. In this case, it's equal to a new copy of the Player class. The new keyword is required whenever you want to create a new object. This tells the device to set aside memory big enough to fit the object. If you don't call new on objects before you use them, your program will have an error.

Next, we have to load the player graphic and set the player's initial position before we can draw them on the screen.

This is where we'll call the Initialize method of our Player class. Since this involves loading a graphic from disk, we will do this inside the game loop's LoadContent() method.

Look down the code, find the method called protected override void LoadContent(). Inside that method, below the SpriteBatch assignment operator, add these lines:

// Load the player resources
Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X,GraphicsDevice.Viewport.TitleSafeArea.Y +GraphicsDevice.Viewport.TitleSafeArea.Height / 2);
player.Initialize(Content.Load<Texture2D>("player"), playerPosition);

We are ready to draw our player. Any time you draw something, you'll draw it via the game loop's Draw() method.

Look down the code, find the method called protected override void Draw(GameTime gameTime). Inside that method, below GraphicsDevice.Clear(Color.CornflowerBlue); add these lines:

// Start drawing
spriteBatch.Begin();

// Draw the Player
player.Draw(spriteBatch);

// Stop drawing
spriteBatch.End();

That's it - that's your drawing code. Notice the Begin() and End() calls. Any further drawing you do will be done between those two calls.

running your game

You've written enough code for now - let's see it in action! To run your game, press CTRL+F5.

If pressing CTRL+F5 doesn't do anything, be sure to right-click on the Shooter project in your Solution Explorer and select Set as Startup Project, then press CTRL+F5 again.

If you've done it right, you'll see the game pop up on your chosen platform. If there are any errors, you'll see them pop up instead in a list at the bottom of the Visual Studio window. It will look something like this.

Image of Shooter Running with a Blue Background and Player Graphic

If you have errors, don't panic. Look below for a downloadable version of this completed step that you can open to keep going error-free.

checkpoint! check your work and get code

Whew! That was a lot of work - but taking the first step is always the hardest.

We recommend you take a second to download a fresh copy of the project with the source code synchronized to the end of this step, especially if you're having trouble getting your code to run.

Just close your Visual Studio environment, click on the link below for the platform you're developing on, then unzip the file and open the enclosed .SLN with Visual Studio. You'll be all caught up!

Creating a Player - Windows Creating a Player - for Xbox 360 Creating a Player - for Phone

Move on to the next step: Taking Player Input

var gDomain='m.webtrends.com'; var gDcsId='dcschd84w10000w4lw9hcqmsz_8n3x'; var gTrackEvents=1; var gFpc='WT_FPC'; /*<\/scr"+"ipt>");} /*]]>*/
DCSIMG