Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Building your First Mobile Game using XNA 4.0
Building your First Mobile Game using XNA 4.0

Building your First Mobile Game using XNA 4.0: A fast-paced, hands-on guide to building a 3D game for the Windows Phone 7 platform using XNA 4.0

Arrow left icon
Profile Icon Thomas Goussaert Profile Icon Brecht Kets
Arrow right icon
€18.99 per month
Paperback Jan 2013 158 pages 1st Edition
eBook
€8.99 €25.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Thomas Goussaert Profile Icon Brecht Kets
Arrow right icon
€18.99 per month
Paperback Jan 2013 158 pages 1st Edition
eBook
€8.99 €25.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €25.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Building your First Mobile Game using XNA 4.0

Chapter 2. 2D Graphics

In the previous chapter, we installed the necessary tools and set up our environment. We can now start by actually drawing some graphics.

In this chapter we will cover:

  • The 2D coordinate system

  • The content pipeline

  • Loading and drawing sprites

  • Translation, rotation, and scale of 2D objects

  • Direction and movement

2D coordinate system


Before we start drawing, we need to have some knowledge about the 2D coordinate system. The 2D coordinate system uses two axes: x and y. The point of origin (being x = 0 and y = 0) is located at the top left corner. The x axis starts at 0 and increases to the right, and the y axis also starts at 0, but increases to the bottom. Note that the length of each axis is partly determined by the orientation.

Let's assume we have a device that supports an 800 X 480 resolution. In portrait, the x axis will be 480 pixels and the y axis 800. In landscape, x will be 800 pixels and y 480.

The orientation will change automatically depending on how you hold the device. By default, landscape left and landscape right are supported, as this does not affect our code. If we want to enable portrait as well, we can set the SupportedOrientations property of the graphics device manager.

graphics.SupportedOrientations = DisplayOrientation.Portrait |
                            DisplayOrientation...

Adding content


Create a new project and call it Chapter2Demo . XNA Game Studio created a class called Game1. Rename it to MainGame so it has a proper name.

When we take a look at our solution, we can see two projects. A game project called Chapter2Demo that contains all our code, and a content project called Chapter2DemoContent . This content project will hold all our assets, and compile them to an intermediate file format (xnb). This is often done in game development to make sure our games start faster. The resulting files are uncompressed, and thus larger, but can be read directly into memory without extra processing.

Tip

Note that we can have more than one content project in a solution. We might add one per platform, but this is beyond the scope of this book.

Navigate to the content project using Windows Explorer, and place our textures in there.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub...

Drawing sprites


Everything is set up for us to begin. Let's start drawing some images. We'll draw a background, an enemy, and our hero.

Adding fields

At the top of our MainGame, we need to add a field for each of our objects. The type used here is Texture2D.

Texture2D _background, _enemy, _hero;

Loading textures

In the LoadContent method, we need to load our textures using the content manager.

// TODO: use this.Content to load your game content here
_background = Content.Load<Texture2D>("Game2D/Background");
_enemy = Content.Load<Texture2D>("Game2D/Enemy");
_hero = Content.Load<Texture2D>("Game2D/Hero");

The content manager has a generic method called Load. Generic meaning we can specify a type, in this case Texture2D. It has one argument, being the asset name. Note that you do not specify an extension, the asset name corresponds with the folder structure and then the name of the asset that you specified in the properties. This is because the content is compiled to .xnb format...

Refactoring our code


In the previous code, we've drawn three textures from our game class. We hardcoded the positions, something we shouldn't do. None of the textures were moving but if we want to add movement now, our game class would get cluttered, especially if we have many sprites. Therefore we will refactor our code and introduce some classes. We will create two classes: a GameObject2D class that is the base class for all 2D objects, and a GameSprite class, that will represent a sprite.

We will also create a RenderContext class. This class will hold our graphics device, sprite batch, and game time objects. We will use all these classes even more extensively when we begin building our own framework in Chapter 6, Building a Basic Framework.

Render context

Create a class called RenderContext. To create a new class, do the following:

  1. Right-click on your solution.

  2. Click on Add | New Item.

  3. Select the Code template on the left.

  4. Select Class and name it RenderContext.

  5. Click on OK.

This class will contain...

Adding movement to the hero


We have a nice static scene now, but it doesn't make much of a game. Let's add some movement to the hero and make him walk over the screen. When he reaches an edge, he will turn back automatically.

The Hero2D class

So we want to add movement to the player. It is best to encapsulate all that new behavior in a class. Let's call class the Hero2D. This class will be responsible for loading the texture, updating the position, and drawing the texture. Make sure the class inherits from GameObject2D class. We could make it inherit from the GameSprite class, but we won't do that. Instead we will add a field of type GameSprite. This is called composition .

In the context of composition, Herb Sutter has said the following:

Prefer composition to inheritance

The reasons why will become obvious when we implement the scene graph and when we make an animated sprite. For now, just go with it.

Fields

The class has three fields, a game sprite, a direction that determines if the player...

Adding animation to our hero


The following topics will guide us on adding animation to our hero.

Sprite sheets

As cool as a sliding hero might be, it would be nice to make him walk instead of slide. We can achieve this by using sprite sheets. A sprite sheet is an image that contains multiple versions of the character in a certain state (walking for example). We then render just a part of the sprite at a time. By switching the parts we render, we can make it appear as if the character is walking. In the following screenshot, you can see the sprite sheet that we will be using. It is 256 pixels wide and contains eight different frames. Each frame is 32 pixels wide by 39 pixels high. Note that it is also possible to have multiple rows in a single sprite sheet.

The GameAnimatedSprite class

The GameAnimatedSprite class is an extension of the GameSprite class. The extra functionality it will offer is drawing sprite animations, this means calculating which DrawRect to use (a parameter we use in our...

Summary


In this chapter, we've learned how to draw 2D images, move them around and use sprite animation. With this knowledge, we could go a lot further: we could make the enemy move and drop rocks (that fall because they are subject to "gravity" and "explode" on impact). We won't do that in this chapter as it uses the same knowledge as we've gained so far, but it is available in the resources that come with this book. If you want, you can take a look at it.

In the next chapter, we will leave the realm of 2D, and add an extra dimension. Let's start drawing 3D models!

Left arrow icon Right arrow icon

Key benefits

  • Building a 3D game for the Windows Phone 7 platform
  • Drawing 2D and 3D graphics on Windows Phone.
  • Using the rich capabilities of the Windows Phone platform.
  • Creating a custom framework step by step that will act as a base for building (future) games.
  • An engaging and hands on beginner's guide to Windows Phone 7 3D game development using XNA 4.0.

Description

With the dawn of the Windows Phone 7 platform, Microsoft has offered us an easy way to create 3D mobile games. In this book, we will build a 3D game for Windows Phone 7 together, taking full advantage of the graphics and touch capabilities, along with the sensors of the platform."Building your First Mobile Game using XNA 4.0" is the book for starting game development on the Windows Phone 7 platform. This book will go over the technical aspects of building games along with designing your own framework. Finally we'll build an actual game together from the ground up! This book will set future mobile game developers in the right direction.The XNA framework empowers us to build 2D and 3D games for PC, Xbox 360 and Windows Phone 7. We will use those capabilities to create stunning 3D games for the Windows Phone 7 platform. We will start by covering the basics like drawing graphics, followed by building a custom framework and end with building a game together!In this book, we will cover drawing 2D and 3D graphics, both static and animations. We will also cover the various ways of handling user input and help set the mood of our game playing both 2D and 3D sound, and accessing the user's media library. The only thing left before building a game is covering several techniques created for making our life easier while building the game, whilst building a framework to do just that. Finally, we'll build a 3D game together that will run on the Windows Phone 7 platform."Building your First Mobile Game using XNA 4.0" is the book you need to get started with mobile game development for Windows Phone 7. Its hands on approach will set you on your way in no time. Let's build some games!

Who is this book for?

This book will cover the building of a 3D game for Windows Phone using XNA. We won't explain the C# programming language itself, nor object-oriented programming. We will however explain the aspects of game development thoroughly, so don't worry if you have never written a 3D game. We will cover all the basics, included the much dreaded math. This is the right book for anyone, regardless of age and gender, if: You are interested in game development You want to start building games for Windows Phone You have some programming knowledge In this book, we will first go over the technical topics, and end up building a 3D game for Windows Phone 7 together!

What you will learn

  • Installing the Windows Phone SDK and the XNA framework
  • Drawing 2D and 3D graphics
  • Mixing 2D and 3D graphics
  • Drawing 2D and 3D animations
  • Playing 2D and 3D sound
  • Playing songs
  • Handling touch input and gestures (tap, swipe, zoom, ...)
  • Building a scene graph and level system
  • Handling collision
  • Creating menus
  • How to build a 3D game!

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 25, 2013
Length: 158 pages
Edition : 1st
Language : English
ISBN-13 : 9781849687744
Vendor :
Microsoft
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 25, 2013
Length: 158 pages
Edition : 1st
Language : English
ISBN-13 : 9781849687744
Vendor :
Microsoft
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 116.97
Building your First Mobile Game using XNA 4.0
€32.99
Microsoft XNA 4.0 Game Development Cookbook
€41.99
XNA 4 3D Game Development by Example: Beginner's Guide
€41.99
Total 116.97 Stars icon
Banner background image

Table of Contents

8 Chapters
Getting Started Chevron down icon Chevron up icon
2D Graphics Chevron down icon Chevron up icon
3D Graphics Chevron down icon Chevron up icon
Input Chevron down icon Chevron up icon
Sound Chevron down icon Chevron up icon
Building a Basic Framework Chevron down icon Chevron up icon
Building a Game Chevron down icon Chevron up icon
Releasing our game Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.