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
€8.99 €25.99
eBook 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
€8.99 €25.99
eBook 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 eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781849687751
Vendor :
Microsoft
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 25, 2013
Length: 158 pages
Edition : 1st
Language : English
ISBN-13 : 9781849687751
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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.