209
James Sugrue Building iOS 5 Games DEVELOP AND DESIGN

Building iOS 5 Games

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

James Sugrue

BuildingiOS 5 Games

DevelOp and DeSiGn

James Sugrue

Building

iOS 5 GamesDevelOp and DeSiGn

Building iOS 5 Games: Develop and DesignJames Sugrue

Peachpit Press1249 Eighth StreetBerkeley, CA 94710510/524-2178510/524-2221 (fax)

Find us on the Web at: www.peachpit.com To report errors, please send a note to [email protected] Press is a division of Pearson Education.Copyright © 2012 by James Sugrue

Editor: Nancy PetersonProduction editor: Myrna VladicDevelopment editor: Bob LindstromCopyeditor: Jessica GroganTechnical Editor: Shaun AustinCover Design: Aren Howell StraigerCover Production: Jaime BrennerInterior design: Mimi HeftCompositor: Danielle FosterIndexer: Emily Glossbrenner

Notice of RightsAll rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contact [email protected].

Notice of LiabilityThe information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of the book, neither the author nor Peachpit Press shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described in it.

TrademarksiOS is a trademark of Apple Inc., registered in the United States and other countries. Open GL is a trademark of SGI, registered in the United States and other countries.Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Peachpit Press was aware of a trademark claim, the designations appear as requested by the owner of the trademark. All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of the trademark. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book.

ISBN 13: 978-0-321-78662-3ISBN 10: 0-321-78662-9

9 8 7 6 5 4 3 2 1

Printed and bound in the United States of America

This book wouldn’t have been possible without the understanding and patience of my wife and children. Towards the end of the book I was stressed,

tired, and grumpy, but they kept me grounded and on track, and more importantly they helped by ignoring my tantrums!

Thanks Kim, Madison, and Alex. I love you all.

First of all, I would like to thank Cliff Colby of Peachpit Press for agreeing to put my pitch for this book into print, and for showing me that California red wine can be pretty good.

A huge thank you to Nancy Peterson for guiding me through the process of creating this book, for her patience, and for keeping the project moving forward.

To Bob Lindstrom, a big thanks for helping me finalize the direction of the book, and taking my words and thoughts and making them better!

I would like to take this opportunity to thank the hard working people at Apple. Without them, none of this would be possible. Thank you and, as we say in New Zealand, “Kia Kaha.”

To Shaun Austin—my old sparring partner from England—cheers, mate. I introduced him to the brilliance of Flight of the Conchords, and he returned the favor by being an excellent technical editor.

ACKNOWLEDGMENTS

iv Building iOS 5 gameS

CONTENTS

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x

Welcome to iOS Games! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xii

Part I USiNG GLKiT iN iOS 5

Chapter 1 Game PROGRammiNG FUNDameNTaLS . . . . . . . . . . . . . . . . . . . . . 2Looking Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4The Game Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Sprites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Sprite Sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

The Game Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

OpenGL ES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Artificial Intelligence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Game Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Chapter 2 aLL aBOUT DeSiGN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8What Is Game Design? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Choosing a Game Genre . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Establishing a Look . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Keeping Everything Under Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Playing by the Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Finding Graphics and Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17But I’m Not an Artist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Let’s Make Some Noise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Chapter 3 USiNG OPeNGL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Creating a New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

Understanding the Basic Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Examining Specific Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Examining the Template App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Making Modifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

COntentS v

Chapter 4 CONTROLLeRS aND SPRiTeS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Understanding Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

Examining the Chapter 4 Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34AbstractSceneController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

GameController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

ViewController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

Drawing Sprites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Vertices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Textures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

Putting Sprites in Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39Interleaved Vertex Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

Sprite Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

MenuSceneController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Chapter 5 aLL aBOUT CONTROL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Changing Scenes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50Changing Scenes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Creating the Player Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53Touch-based control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Tilt-based Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

Virtual Joystick Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Checking Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

Chapter 6 ShOOT TO KiLL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Enemy Sprite Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64Strafing Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

Missiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

Enemy Movement and Intelligence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68Creating Dynamic Difficulty Using AI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

DumbSprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Diagonal Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Diagonal Sprite AI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Kamikaze Sprite AI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

vi Building iOS 5 gameS

Chapter 7 BLOwiNG STUFF UP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74Collision Detection Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76Bounding Box Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

Bounding Circle Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

Per Pixel Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Collision Detection in Raiders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79Adding Detection Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Collision Checks and Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Collision Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

Setting Off Explosions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83Adding Sound Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

Chapter 8 FiNiShiNG TOUCheS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88Building a Scoreboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90Rendering Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Keeping Score . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94Player Lives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

Winning the Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

Starting Over . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

Are We There Yet? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

Chapter 9 BeiNG SOCiaL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100Game Center Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Using Leaderboards, Achievements, and Scoring . . . . . . . . . . . . . . . . . . 104Building Leaderboards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

Sending Scores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

Creating Achievements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Completing Game Center Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

Sending a Tweet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110Using TWTweetComposeViewController . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

Sending a Tweet Without a ViewController . . . . . . . . . . . . . . . . . . . . . . . . . 113

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

COntentS vii

Chapter 10 iaD, aiRPLay, aND iN-aPP PURChaSeS . . . . . . . . . . . . . . . . . . . . . 116Using iAd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

Getting AirPlay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

Supporting In-App Purchases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124Creating and Processing an IAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

Part II USiNG OPeNGL eS 2 .0

Chapter 11 PRePaRiNG FOR OPeNGL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132Creating a New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

Readying the App for OpenGL ES Conversion . . . . . . . . . . . . . . . . . . . . . . 135Creating Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

Preparing the Rendering Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

Changing the ViewController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142

Creating the Program Object and Linking Shaders . . . . . . . . . . . . . . . . . . 143

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

Chapter 12 RaiDeRS: OPeNGL eS STyLe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152Revisiting Sprites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154Changing the Sprite Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

Loading a Texture in OpenGL ES 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

Applying Shaders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158Using the Fragment Shader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158

Implementing Translations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

Changing Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163Editing ViewController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

Modifying GameController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

Altering BitmapFont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

appendix a iNTRODUCiNG OBJeCTive-C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168Syntax Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

Header and Implementation Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171Import Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

viii Building iOS 5 gameS

@interface declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

Implementation File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

Instantiating Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

Retain/Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

New to iOS 5: ARC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178

Protocols and Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179

Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

appendix B FURTheR ReaDiNG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182Objective-C / iOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

OpenGL ES 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

Games Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .186

COntentS ix

There’s never been a better time to bring your creative ideas to life by program-ming a game for iOS. The Apple App Store gives you a huge opportunity to get your game in front of millions of potential customers; game distribution has never been easier or so far-reaching.

Not only do you have access to millions of potential customers, you also have access to cutting edge development tools and hardware. The iPhone and iPod Touch are effectively computers with power that outpaces the desktop computers of just a few years ago. They allow you to create some fantastic games with few of the hardware and software limitations of earlier handheld devices.

This book will introduce you to the world of game design and programming for iOS 5.

The book is aimed at people who have already done some programming. It’s best if you have Objective-C experience, but it isn’t required. Be aware, however, that no time will be spent reviewing programming basics, and the coding constructs won’t be explained at all. Therefore, you’ll need a functional competence in some form of programming.

You’ll find this book most useful if you’re an Objective-C developer, who has always wanted to dabble in OpenGL ES, or create your own game, but didn’t know where to start.

Each chapter builds on the previous chapter, examining and explaining a core part of game development as you build an iOS game.

Along the way, you’ll explore OpenGL ES and game development in a clear and accessible manner. You’ll learn the fundamentals of game creation, rather than exotic techniques or advanced methods.

This means that the game project you will build puts simplicity first. The code was intended to be easy to understand, and as such may not represent the most refined or fastest programming. But, it will get you from novice to game program-mer as efficiently as possible.

Finally, although OpenGL ES 2.0 plays a key role in our game project, this book isn’t a detailed OpenGL guide. In fact, most of the OpenGL ES code is hidden behind Apple’s new GLKit framework. GLKit makes it possible to create games without being encumbered by the details of OpenGL ES.

When you finish the book, you’ll have a solid foundation in game development and design, and will be in a good place to begin creating your own best-selling game.

INTrODuCTION

x Building iOS 5 gameS

i

WELCOME to iOS GAMES!

tools

These tools are required for designing and developing games in iOS 5.

XCOde

Xcode is the development environment you will use to program iOS apps and games. The latest version, used in this book, is 4.2 with iOS SDK 5.0. Xcode is a total development environment offering coding, interface design, building, debugging, testing, and profiling in a single interface.

iOS SimulatOr

The iOS Simulator lets you test your apps and games as if they were running on one of three different iOS devices: a standard iPhone 320x480, a retina iPhone 640x960, and an iPad 1024x768. You can test for all three devices without owning the actual hardware.

WELCOME to iOS GAMES!

Developing and designing games for iOS requires a number of tools and frameworks. For

instance, you’ll use Xcode, a free integrated development environment (IDE) from Apple;

and Objective-C, the native language used in iOS.

Along with the Xcode/Objective-C combo you’ll need a few other tools and applications

to create game. Here’s a quick overview of some of them.

xii Building iOS 5 gameS

other tools

Some tools aren’t required, but are handy during the development process.

Preview

Preview does much more than simply previewing images and PDFs. It is also an excellent basic image editor for cropping, cut-ting, and scaling graphics.

HierO

Hiero converts a font set to an image file that can be used when rendering fonts in OpenGL ES.

audaCity

Audacity is an open source audio editor that opens many sound file formats. It allows you to trim sound clips, adjust sound levels, and much more when creating sound effects for your game.

Pen and PaPer

It may seem like “retrotech,” but when designing your game, pen and paper are invaluable for prototyping your ideas. As a preliminary step in game design, you can sketch game objects and interface, quickly com-mitting your ideas to the concept phase.

xiii

This page intentionally left blank

4

CONTrOLLErS AnD SprITES

In this chapter you will be

introduced to the classes that combine to form the

foundation of the game engine. Then, you’ll create

the sprite classes that draw and control the game characters

on the screen.

Beginning with this chapter, you’ll be dealing with a lot of code.

Instead of writing the code from scratch, you can follow along

with the completed code by downloading it from the book’s web-

site, www.peachpit.com/iOSGames. While examining the code,

it will be useful to identify the key sections and to understand

their purpose.

31

You learned a bit about controllers in the previous chapter. In Raiders, controllers are classes that manage the game flow, and are responsible for rendering scenes and managing sprite objects.

TErMS to pLAy WIth

Before you delve into the code, you should understand a few gaming and programming terms:

Game Scenes

Games are a lot like movies because they are made up of distinct sections that combine to create the whole. In raiders (as in movies), these sections will be called scenes, and each scene will have a scene controller.

Examples of common scenes are:

J menuscene—Controls the game’s starting menu in which the player can change settings, choose levels, and start game play

J highscorescene—Displays the high score tables

J level scene—Each level in a game has its own numbered scene, such as Level1 Scene, Level2 Scene, and so on.

J Gameoverscene—Plays when the player loses all his lives

abstraction

Abstraction is a programming technique that uses a base or parent class to define common characteristics for any child classes. This base class is called an abstract class.

Using a real world object as an example, you might have an abstract class called Door, which has a method called Open. This is logical because all doors must open, but this leaves the implementation of how the door will open to the specific door. For example, a child class called SlidingDoor might have a method called Open, but the implementation would make the door slide.

UnDErSTAnDInG CONTrOLLErS

32 ChaPter 4 COntrOllerS and SPriteS

TErMS to pLAy WIth (continued)

The benefit of abstraction is that the “blueprint” can include just the parent Door, and the actual implementation or mechanics of that door can be cre-ated later.

In raiders, an abstract class called AbstractSceneController is the base class that all the other scene controllers inherit from. This abstract class allows the game engine to render any scene without knowing the specifics of that scene. It also allows you to use one class to control all the scenes and just

“plug in” the required scene at the required time.

Game Controller

Continuing with the movie analogy, the game controller is like a director. It manages which scene is currently active, and also controls game state, scores, game levels, and so on.

In this chapter, the game controller will do only two things:

J manage the active scene

J Tell the active scene to render itself

In future chapters, the game controller will be assigned many more functions.

Singleton

Singleton is the name given to a class that has only one running instance of itself. This class is used when you need one object to coordinate actions and resources across the app. Because the app is restricted to one instance of a singleton class, the class’ resources are available on a global level. That is, the instance is available in the same state to all other classes of the app that need it. In raiders, the GameController is a singleton because it requires the same instance throughout the project.

Singletons are used a lot in modern programming, usually when caching resources or accessing shared resources and code.

underStanding COntrOllerS 33

ExAMINING the ChaPter 4 prOjECT

Open Raiders.xcodeproj in Xcode 4 and look at the files pane to the left. You will notice a lot of new files and what appear to be folders (Figure 4.1).

Now, let’s look at the new files in increasing order of complexity.

aBstraCtsCeneController

AbstractSceneController is the abstract class for the scenes. It is a very simple class with only two external methods and one private method.

playScene is implemented by its child classes, and each instance will be par-ticular to that scene, because it includes the rendering code for the scene.

addSprite is used internally to the class and adds a sprite to the list of sprites in the scene. The list of sprites is used in updateScene.

updateScene loops though the list of sprites in the current scene and creates the transformations required to render the sprites. You’ll learn more about updateScene in the “Drawing Sprites” section in this chapter.

FiGURe 4 .1 Files pane

note: from this point forward, files will be described by their class names, unless otherwise stated. you can assume that all files have an .m and an .h file.

34 ChaPter 4 COntrOllerS and SPriteS

GameController

In this project, the GameController class has a property called currentScene of type AbstractSceneController, that holds the active scene; and it has a method called playCurrentScene that calls the playScene method of the currentScene.

You may find something in GameController that you have not seen before. At the top of the .m file is the following:

@interface GameController (private)

- (void)initScene;

@end

This code is called a category in Objective-C. It adds methods to the class with-out the need to subclass. We could have put initScene in the .h file, but then it would be available to other code using the GameController class. By adding it as a category, it signals that this method is private (internal) to the GameController class and shouldn’t be called from outside the class.

In this specific case, initScene is called when the GameController class is first instantiated, and it assigns the MenuSceneController to the currentScene property, which allows the menu scene to automatically appear when the app is launched.

The other line of code that might catch your eye is the following:

SYNTHESIZE_SINGLETON_FOR_CLASS(GameController);

This code uses a #define macro that is defined in SynthesizeSingleton.h (thanks to Matt Gallagher from www.CocoaWithLove.com). This block of code takes the class name as a parameter and creates the singleton construction code for us. As a result, you don’t have to write the same boilerplate code to create a singleton in every class that needs it. Use this approach in other projects to save a lot of time

“reinventing the wheel.”The last method is updateWorld, in which all of the objects in the “world” update.

eXamining tHe CHaPter 4 PrOjeCt 35

vIeWController

The biggest change in the code from Chapter 3 is in ViewController. Previously, ViewController was handling all the setup, transformations, and rendering code. In this chapter, we use other classes to handle that code, and the GameController class is used to handle the rendering tasks. A new variable, sharedGameController of type GameController, is a link to the game controller—and if you look in glkView:drawInRect—you’ll see that the code has been replaced with a single call:

[sharedGameController playCurrentScene]

In update, you’ll see a single call to [sharedGameController updateWorld].This is the power of abstract classes. In the earlier version of the project, meth-

ods had a lot of transformation and rendering code. But now the code is abstracted into other classes. In the current project, the current scene will be rendered, which in this case is the Menu scene.

This approach makes reading and maintaining code much easier because each distinct class is responsible for rendering its own scene. It’s therefore easier to go to the appropriate class to understand the flow of the app because you know the code relating to the menu will be in the menu scene.

36 ChaPter 4 COntrOllerS and SPriteS

1

2

3

4

Triangle 2

Triangle 1

OpenGL ES is a powerful graphics rendering API for creating 2D and 3D graphics. Because all objects in OpenGL ES are made up of triangles, you can create any object by combining triangles of various sizes. For example, a square or rectangle consists of two triangles combined.

vertICes

A triangle is made up of individual points, each called a vertex, which is a geometric point in space. In Raiders, a vertex will be an x,y point; but, in reality, each vertex in the game is a point in 3D space that always has a z of 0. Because the game is in 2D, the rendering is performed on a single plane in 3D space.

To create a square from two triangles you only need four vertices as shown in Figure 4.2. OpenGL is smart enough to close the triangles from vertices 1-3 and 4-2. Once you start adding triangles, you can see the power of this. To create a house image from the square, you would add another triangle but would create only one more vertex (Figure 4.3).

FiGURe 4 .2 Square made from two triangles with four vertices

note: this next section is going to get quite intense, so it is recommended that you find a quiet place to read. Concentration will be required.

draWInG SprITES

drawing SPriteS 37

1

2

3

4

Triangle 2

Triangle 1

Triangle 3

5

textUres

A 2D game like Raiders only requires you to create quads, which are two triangles combined to create a square.

By itself, a quad is just a collection of points of a certain size. Once the quad is created, a texture is needed for it. A texture is a graphic that covers the top of the quad vertices, much like a dust cover covers a book or a tea cosy covers a teapot. This technique is called texture mapping.

OpenGL ES imposes a limitation on all textures. A texture’s width and height must be a power of two: 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024. Because iOS devices prior to iPad, iPad 2, and iPhone 4 could not recognize textures greater than 1024 x 1024, you should consider that the maximum size for a texture in an iOS game. However, the image doesn’t need to be square, so it could be, for example, 64 x 32 pixels in size.

FiGURe 4 .3 Adding another triangle creates only one more vertex.

38 ChaPter 4 COntrOllerS and SPriteS

PUttInG SprITES In ACTION

In the file Sprite.m, you will see the following arrays:

static const GLfloat vertices[] = {

0.0f, 0.0f,

1.0f, 0.0f,

0.0f, 1.0f,

1.0f, 1.0f,

};

static const GLfloat texCoords[] = {

0.0f, 1.0f,

1.0f, 1.0f,

0.0f, 0.0f,

1.0f, 0.0f,

};

static const GLushort cubeIndices[] =

{

0, 2, 1,

1, 2, 3,

};

The first array defines the vertices of the quad. The second array defines the texture mapping coordinates.

Putting SPriteS in aCtiOn 39

(0,1)

(0,0)

(1,1)

(1,0)

A texture is always mapped using a quad with the range of 0-1 in height and width (Figure 4.4), which is called a texture coordinate system. The texture coordinate system is usually refered to as the (s,t) system, while the geometry system is referred to as the (u,v) system. So when mapping a texture to a quad, it is said that you are mapping (s,t) coordinates onto the (u,v) coordinates, which is sometimes called UV mapping in 3D applications.

Using Figure 4.2 as the reference for the (u,v) coordinates and Figure 4.4 for the (s,t) coordinates, vertex 1 would map to coordinates of (0,0), vertex 2 of (0,1), and so on.

You don’t need to use the full 0-1 range to map the texture. For example, you could map half the texture by using the (s,v) coordinate range of (0,0), (1,0), (0, 0.5), (1, 0.5).

FiGURe 4 .4 Coordinates for a texture to be mapped

40 ChaPter 4 COntrOllerS and SPriteS

T1

V1

V1

T2

V2

C1

T1

V3

T1

T2

V2

V2

V1 C1 T1 V2 C2 T2 …

Interleaved vertex data

In most beginning examples of OpenGL ES, it is usual to have separate arrays for vertex points and texture vertex points. In fact, Raiders does just that, as you can see in Figure 4.4.

This is a reasonable approach and is relatively easy to read and maintain, which is all that is necessary for simple quads with textures.

For the sake of full understanding, however, you should know that for more complicated models, Apple recommends using interleaved vertex data, which uses an array of structs rather than the series of arrays. In a struct, data is stored in a single structure (array) and interleaved together. So the information for vertex 1 is read together, then the information for vertex 2 is read together, and so on (Figure 4.5). This technique provides memory locality for each vertex and is superior to separate arrays (Figure 4.6).

FiGURe 4 .5 Interleaved vertex data

FiGURe 4 .6 Separate vertex arrays

Putting SPriteS in aCtiOn 41

sPrIte Class

With a background in place, it’s time to look at Raider’s Sprite class. The Sprite class is instantiated with the method initWithImageNamed which takes a NSString as a parameter that is the name of an image file to be used as a texture.

initwitHimagenamedLook at the code in initWithImageNamed (code first, then description):

textureInfo = [GLKTextureLoader textureWithCGImage: p [UIImage imageNamed:imageName].CGImage options:nil error:nil];

name = textureInfo.name;

self.width = textureInfo.width;

self.height = textureInfo.height;

Prior to the introduction of GLKit, it took many, many lines of code to load images into a texture buffer. As you can see above, you can now do this with only one line of iOS 5 code.

The next line assigns the texture’s OpenGL-friendly name to a property for later use. The width and height of the image are also stored for later use.

[self initVertexInfo];

[self initEffect];

The next two lines allocate and assign the vertex information into memory, and initialize a GLKit effect that will create the appropriate shaders.

42 ChaPter 4 COntrOllerS and SPriteS

initverteXinFOThis method sets up the buffers for holding the quad and texture vertices.

glEnable(GL_BLEND);

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

These two lines of code are needed to allow the textures to be mapped with a transparent background.

glEnableVertexAttribArray(GLKVertexAttribPosition);

glVertexAttribPointer(GLKVertexAttribPosition, 2, p GL_FLOAT, GL_FALSE, 0, vertices);

glEnableVertexAttribArray(GLKVertexAttribTexCoord0);

glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, p 0, 0, texCoords);

glBindVertexArrayOES(0);

The next four lines are the meat of this method. They set up and assign the quad vertices and the texture coordinates into memory buffers. The use of the GLKit constants GLKVertexAttribPosition and GLKVertexAttribTexCoord0 provides vertex position and texture coordinates to the shader. Either a hand-coded shader, or one that GLKit will create automatically.

initeFFeCtAs you’ve learned, in “vanilla” Open GL ES 2.0 code, shaders must be written that calculate rendering effects. They are written in their own languages, and while they can be complicated to write and understand, they aren’t really necessary for a simple 2D game. Luckily, Apple has abstracted shaders away in GLKit by introducing a set of effects classes for handling shading, lighting, and texturing.

effect = [[GLKBaseEffect alloc] init]; p effect.texture2d0.name = name;

effect.texture2d0.enabled = GL_TRUE;

effect.texture2d0.target = GLKTextureTarget2D;

effect.light0.enabled = GL_FALSE;

Putting SPriteS in aCtiOn 43

The effect usage in Raiders is minimal. Because Raiders has no lighting or shading and only 2D textures, the code is fairly simple. The texture name that was assigned in initWithImageNamed: is assigned to the effect and the lighting is switched off. You can apply different lighting effects to the world, such as diffuse or spot lighting. This isn’t needed for our 2D game; but in a 3D game, lighting can give a sense of depth and extra realism.

uPdatetranSFOrmSupdateTransforms creates the projection matrix, which transforms coordinates in an object from vector space to screen space. Raiders uses an orthographic pro-jection that has no vanishing point or perspective, and places parallel lines of an object at a constant distance. Because no perspective is applied in this projection, objects can’t get distorted.

GLKMatrix4 projectionMatrix = GLKMatrix4MakeOrtho(0.0f, 320, 0.0f, p 480, 0.0f, 1.0f);

effect.transform.projectionMatrix = projectionMatrix;

GLKMatrix4 modelViewMatrix = p GLKMatrix4MakeScale(self.width, self.height, -1.0f);

modelViewMatrix = p GLKMatrix4Multiply(transformation, modelViewMatrix);

effect.transform.modelviewMatrix = modelViewMatrix;

The first line sets up the projection matrix to the width and height of the screen. Then the matrix is assigned to the effect.

Another matrix is created that will act as the transformation matrix for the sprite. It is first scaled to the size of the image, then moved using the transformation matrix that is created if the sprite needs to be positioned at specific screen coordinates (explained in the next section). Then, this new matrix is assigned to the effect.

44 ChaPter 4 COntrOllerS and SPriteS

WHAT Is a MATrIx anyWay?

As this book is aimed at beginning game design and development, an in-depth study of 3D math, matrices, and transformations is beyond its scope. You can delve into these subjects when you understand the basics of game design and development.

However, in a nutshell, a matrix is a rectangular array of numbers (in graphics, usually 4x4, 3x3, or 2x2). matrix transformations are well understood in math-ematics, and using standard matrix forms, transformations—such as rotation, scaling, and translations—are easily calculated and implemented in a render-ing system such as OpenGL ES.

A wealth of information is available on these subjects, and a few good books and websites are listed in Appendix B: “Further reading.”

drawatPOSitiOndrawAtPosition allows the sprite to be rendered at a specific point. The position parameter passed in is stored in a property for later use, and a boolean variable called dirtyBit is set to YES. Finally, the draw method is called.

drawThe draw method does the actual sprite rendering.

if (dirtyBit) {

transformation = GLKMatrix4MakeTranslation p (position.x, 480.0 - position.y – self.height, 0.0f);

}

Putting SPriteS in aCtiOn 45

First, the method checks to see if the dirtyBit is set. If so, a transformation matrix is created based on the position in which the sprite should be drawn. Because OpenGL ES has coordinates opposite to screen coordinates, the y coordinates must be subtracted from the height of the viewport. The transformation matrix is then used by the update method from the GLKView.

[effect prepareToDraw];

glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, cubeIndices);

dirtyBit = NO;

This renders the quad and the texture on the screen, given the cubeIndices array of vertex information defined earlier.

The last line renders to the screen all the information that was previously set up.

menUsCeneController

Sprites can now be drawn onto the screen, so all you need is a scene in which to do so. Most games start with a menu screen, and Raiders will be no different. The last class to explore is MenuSceneController.

MenuSceneController is the first scene that the player will see after opening the game. At this stage, we will include just a background sprite and a sprite to act as a play button.

At the moment the play button doesn’t do anything. We’ll save that for the next chapter.

46 ChaPter 4 COntrOllerS and SPriteS

You have learned a lot of new techniques, code, and terminology in this chapter. This will serve as core knowledge to be built on in upcoming chapters. If you didn’t quite grasp any of the concepts, you might want to review the chapter, along with the project source code.

In this chapter, you have seen how the game controller is the game’s director, directing resources and the flow of scenes. You have learned about points, vertices, textures, (u,v) and (s,t) mapping, interleaved vertex data, and how to use all of these to render sprites to the screen.

In the next chapter, you will create the game character classes, so the game will respond to touches, and you’ll learn how to move between scenes.

WraPPInG up

wraPPing uP 47

#define macro, 35@class declaration, 171@implementation declaration, 173@import declaration, 171@interface declaration, 171–172, 179@synthesize command, 1732D games. See also Raiders

depth values in, 138lighting effects for, 44moving objects in, 160and OpenGL, 6, 37and quads, 38shaders for, 43

2D graphics, 6, 372D textures, 443D games, 44, 138, 1843D graphics, 6, 373D math, 45, 1613D transformations, 161

aabstract classes, 32–33, 34, 36abstraction, 32–33AbstractSceneController class, 33, 34,

35, 79acceleration variable, 55accelerometer, 7, 14, 54achievements, 107–109action games, 10, 63ActionItem class, 50, 51, 53, 76, 104activeEnemies variable, 96ADBannerView protocol, 118–120AddDelegate file, 151addSprite method, 34AdMob, 122advertising framework, 118–122AdWhirl network, 122AI

creating dynamic difficulty using, 68

defined, 7for Diagonal Sprite, 70from gaming point of view, 68importance of, 7for Kamikaze Sprite, 72standard algorithms for, 7

AIFF files, 19, 85AirPlay, 123, 129algorithms, game programming, 7, 68,

72, 76, 185alloc method, 175, 176Angry Birds, 10, 124animation, 136, 138AppDelegate file, 24, 103, 134, 151Apple

advertising framework, 118App Store, xideveloper program, 22Game Center, 102 (See also Game

Center)GLKit (See GLKit)Objective-C documents, 181Retina Display, 17second display feature, 123Twitter framework, 110

Apple TV, 123App Store, Apple, xiARC, 178. See also Automatic

Reference Counting featurearrays

clearing sprite, 97for defining quad vertices, 39explosion, 83for interleaved vertex data, 41and matrix transformations, 45

artificial intelligence, 7. See also AIartists, 18assigning vs. copying, 93Audacity, xiii, 19audio editor, xiiiaudio effects, 18–19, 84–86audio formats, 19Audio frameworks, 84–86AudioServicesPlaySystemSound

method, 85audio streaming, 123AudioToolbox, 85, 163Automatic Reference Counting

feature, 134, 178autorelease method, 177AVAudioPlayer framework, 84–86AVPlayer, 86

Bbackground music, 85barriers, 16base classes, 32–33Beginning Math and Physics for Game

Programmers, 185BitmapFont class, 92, 166bitmaps, 157Blair Medium font, 92bounding box detection, 76–77, 79bounding circle detection, 77, 79bounds checking, 60bounds property, 50braces, 171buffers, 138–139Bundle Identifier, 102

Ccaching resources, 33CADisplayLink timer, 136, 138, 165CAFF files, 19, 85Campbell, Duncan, 184canFireMissiles property, 95categories, 35, 179–180C-based sound effects framework, 85C/C++ methods, 25, 170changeScene method, 52character sprites, 93checkForCollisions method, 86child classes, 32, 34Chopper 2 game, 59circular bounds, 77classes

adding methods to, 35extending functionality of, 179importing, 171instantiating, 175managing game flow with, 32–33

Class Prefix, 22CocoaWithLove.com, 35cocos2d game engine, 5, 6code

downloading from book’s website, 31

reading/maintaining, 36reusing, 6, 155

INDEx

186 indeX

collision detectiondefined, 76methods, 76–78purpose of, 73in Raiders, 76, 79–82, 162

collision logic, 80–82Common.h file, 52Company Identifier, 22compiler cheats, 173compiling shaders, 143contract/freelance sites, 18controllers, 32controls, 53–59

allowing player to choose, 58importance of, 14novel approaches to, 59purpose of, 7tilt-based, 54–55touch-based, 53, 58, 162virtual joystick, 55–58

coordinates, mapping, 40copying vs. assigning, 93Core Techniques and Algorithms in

Game Programming, 185Cox, Brad, 169C-style syntax, 169currentLives property, 97currentPosition property, 53, 60currentScene property, 35currentScore property, 94, 97currentSprite method, 83

dDalmau, Daniel, 185deaths, player, 94#define macro, 35design documents, 10Device Family, 22Diagonal Sprite, 64, 69–71difficulty levels, 16, 98dirtyBit variable, 45–46distance formula, 69doAnimation method, 83Doom, 68drawAtPoint method, 53drawAtPosition method, 45

draw method, 45–46, 150, 159, 161, 165drawPlayer method, 53drawTextAtPoint method, 93drawView selector, 141driving games, 7DumbSprite, 64, 68–69dynamic difficulty, 68

eEAGLContext, 138EAGLView layer, 140effects classes, 43–44elevator pitches, 11Embedded Systems, 6. See also ESenemy missile collisions, 79, 82enemy movement, 15, 68–72EnemySprite class, 64, 79, 82enemy sprites

class considerations, 65creating multiple types of, 15importance of, 63, 64keeping track of number of, 96killing, 15missile graphics for, 66vs. player sprites, 53

enemyType property, 64engines, game, 5–6ES 1.1, 6, 21. See also OpenGL ESES 2.0, 6, 21. See also OpenGL ESESMatrix structure, 155esTranslate method, 155, 161Explode class, 83explosions, 83–86extension methods, 179

ffiles pane, 34font rendering, xiii, 91–93formulas

distance, 69slope of line, 70, 71

fragment shader, 158frame buffers, 138freelance artists, 18

GGallagher, Matt, 35game AI, 68. See also AIGame Center, 102–109

disabling, 103enabling, 102features provided by, 104purpose of, 102sending scores to, 106

GameController class, 35, 52, 94, 97, 165

game controllers, 33game controls, 53–59

allowing player to choose, 58importance of, 14novel approaches to, 59purpose of, 7tilt-based, 54–55touch-based, 53, 58, 162virtual joystick, 55–58

game descriptions, 11game design, 9–19

changing, 9, 19choosing controls, 14choosing genre, 10–11establishing a look, 12–13finding graphics/sounds, 17–19importance of, 10programming knowledge required

for, xirole of sound in, 12setting rules, 15–16sketching, xiii, 12tools, xii–xiiiand view modes, 12–13

game developmentfundamentals, 3–7further reading on, 185terms, 32–33tools, xii–xiii

game engines, 5–6game genres, 10–11game graphics, 13Game Kit framework, 102, 104, 107,

109, 163game loop, 4, 84game objects, 4, 7

indeX 187

“game over” message, 94, 95GameOverScene, 32game rules, 12, 15–16games. See also iOS games

adding social features to, 101–115converting from GLKit-based to

OpenGL ES, 135–151creating in Xcode, 22creating multi-level, 98designing (See game design)displaying ads in, 118–122further reading on developing, 185increasing “stickiness” of, 101initializing, 97math/physics programming for, 185multiplayer, 102scoring, 90, 94–96selling items in, 124–128sharing information about, 102

game scenes, 32. See also scenesgame states, 24gaming network, 102–103gaming terms, 32–33genres, game, 10–11geometry system, 40getter methods, 173GIMP image editor, 17GKAchievementViewController, 107GKLeaderBoardViewController, 107GLES2, 153, 154, 167. See also

OpenGL ESGLKit

effects classes, 43–44how it works, 29implementing translations in, 160and iOS versions, 21, 133limitations of, 133, 153loading textures in, 156–157purpose of, xi, 21, 29, 133rendering scenes in, 150and shader files, 25, 26updating scenes in, 136vs. OpenGL ES, 150

GLKTextureLoader class, 156GLKView, 25, 46GLKViewController, 25, 104GLView, 136, 137, 138, 140, 142goals, 107

Google AdMob, 122graphics. See also images

creating, 13, 17, 37–38missile, 66purchasing, 18scaling, xiiiusage rights for, 18

graphics editors, 13, 17graphic stock websites, 18gyroscope, 7

hhasAnimationFinished variable, 84hasBeenShot property, 79, 80, 95hasBeenTapped method, 50header files, 171–172. See also .h files.h files, 24, 25, 34, 171hideAd method, 121Hiero, xiii, 91–93HighScoreScene, 32high score table, 104Hillegass, Aaron, 184house image, 37–38

IiAds, 118–122, 129IAP, 124–128, 129image editors, xiii, 13, 17images. See also graphics

copying, 157cropping, xiiihouse, 37–38loading into texture buffer, 42previewing, xiiiresizing, xiii, 163

implementation files, 171, 173–174. See also .m files

import declarations, 171in app purchases, 124–128, 129income, generating, 117, 118, 124, 129inheritance, 50, 51, 179initEffect method, 43–44initialization code, 24init method, 85, 97, 140, 175initScene method, 35, 52, 97initVertexInfo method, 43

initWithImageNamed method, 42intelligence, 68. See also AIintelligent agents, 7interface declaration, 171–172, 179interface files, 171interleaved vertex data, 41iOS

advertising framework, 118–122audio formats, 19devices (See specific devices)further reading on, 184games (See iOS games)language behind, 169 (See also

Objective-C)memory errors, 178memory management, 176and multitasking, 24and OpenGL, 6, 21, 153playing sound in, 84–86Simulator, xii, 23social gaming network, 102–103and textures, 38top source of bugs in, 178and touch-based control, 53and Twitter framework, 165

iOS games. See also gamescharacteristics of good, 11choosing genre for, 10–11creating in Xcode, 22designing, xi (See also game design)and device orientation, 12–13game controls for, 14popular game engines for, 5saving game state for, 24time considerations, 11

iOSGames website, 31iPad

and game genres, 10and OpenGL, 6and player controls, 59screen-size considerations, 17and second display feature, 123and textures, 38

iPhoneaccelerometer, 54–55core set of apps for, 24and game genres, 10and OpenGL ES, 6, 21

188 indeX

screen-size considerations, 17testing apps for, 23and textures, 38and tilt-based control, 54and touch-based control, 53

iPhone 3D Programming, 184iPhone Application Development

for iOS 4: Visual QuickStart Guide, 184

iPod Touch, 6, 17isGameOver property, 96, 97isMissileActive property, 66–67isMoving property, 56, 57isReturning variable, 69isStrafing property, 64iStockphoto.com, 18itemStrafing variable, 80, 81iTunes Connect, 102, 104, 124

Jjoystick control, virtual, 55–58

kKamikaze Sprite, 64, 72keys values, 52

llandscape mode, 12–13latency, 85, 86layoutSubviews method, 141–142leaderboards, 104–105, 106Level1SceneController class,

52, 54, 97levels, 16, 96, 98Level Scene, 32lighting effects, 43–44line-slope formula, 70, 71lives, player, 15, 94–96loadShaders method, 150loops, 4, 84Love, Tom, 169

mmain.m file, 24MainWindow.xib file, 24Majic Jungle Software, 59mapping, texture, 38, 39–40maps, 10masks, 5math programming, 185matrices, 45, 161matrix math, 160–162memory buffers, 43memory errors, 178memory management, 176memory space, 157MenuScene, 32MenuSceneController, 35, 46, 51, 104menu screen, 46messaging, 170.m files, 24, 25, 34, 171, 173Mighty Eagle, 124missiles, 4, 16, 66–67, 79, 95mixins, 179Model-View-Controller technique, 24movement, enemy/player, 15–16,

68–72MP3 files, 19MPEG files, 19multi-level games, 98multiplayer games, 102multitasking, 24Munshi, Aaftab, 184musical score, 18music, background, 85MVC programming technique, 24

nn4te.com, 91named parameters, 170navigation code, 25New Project command, 22nib files, 25. See also .xib filesnon-player characters (NPCs), 7NPOT textures, 156NSCoding protocol, 106NSDictionary variable, 52NSString object, 42, 175

oObject-C Programming: The Big Nerd

Ranch Guide, 184Objective-C, 169–181

Automatic Reference Counting feature, 178

AVAudioPlayer framework, 85calling methods in, 170categories, 35, 179–180creators of, 169further reading on, 184header files in, 171–172implementation files in, 171,

173–174instantiating objects in, 175memory management in, 176methods, 25, 171protocols, 179–180resources, 181retain count, 177vs. other object-oriented

languages, 170object-oriented languages, 169, 170objects

instantiating, 175moving, 160releasing, 177

onscreen controls, 14, 59OpenAL framework, 86OpenGL, 6, 25. See also OpenGL ESOpenGL Embedded Systems, 6.

See also OpenGL ESOpenGL ES

challenges of using, 21converting Raiders to, 153–167creating 2D/3D graphics with, 37creating transformations in, 155, 167font support, 91further reading on, 184implementing translations in,

160–162and interleaved vertex data, 41and legacy iOS devices, 133limitation on textures in, 38loading textures in, 156–157and Objective-C, 169

indeX 189

OpenGL ES (continued)readying app for conversion to,

135–151setting up empty template in, 134Shader Language, 25, 29and shaders, 43, 143–151and template app, 25transformations in, 45updating scenes in, 136versions, 6vs. GLKit, 150

OpenGL ES 2.0 Programming Guide, 184

Open Graphics Library, 6. See also OpenGL

open source audio editor, xiiiopen source websites, 18, 19orthographic projection, 44, 160

Pparameters, named, 170parent classes, 32parent sprite class, 154path finding, 7, 68PDFs, xiiipencil sketches, xiii, 10, 12per pixel detection, 78perspective, 44Photoshop, 13, 17physics programming, 185pixel-based detection, 78pixel-based graphics editors, 17Pixelmator, 13, 17Plants vs. Zombies, 10playCurrentScene method, 35player

controls, 53–59lives, 15, 94–96missile collisions, 79, 82movement, 15–16

PlayerSprite class, 53, 60, 64, 79playExplosionEffect method, 85, 86playing loops, 84playScene method, 34, 35, 79, 80portrait mode, 12–13POT textures, 156, 163, 166Preview tool, xiii

private methods, 35products, selling, 124–128programming. See also code

further reading on, 184–185games vs. other applications, 4terms, 32–33tools, xii–xiii

projection matrix, 44projectionMatrix variable, 160projects

adding Twitter framework to, 110basic files needed for, 23–25converting from GLKit-based to

OpenGL ES, 135–151creating, 22, 134naming, 22, 134saving, 22

protocols, 179–180puzzle games, 7, 10Python, 179

Qquads, 38, 39–40, 43QuartzCore framework, 135

rracing games, 58, 123, 124Raiders

AI in, 68changing scenes in, 50–52collision detection in, 76–82converting to standard OpenGL ES,

153–167creating achievements in, 107–109creating multiple levels in, 98creating project, 22dynamic difficulty in, 68effect usage in, 44elevator pitch for, 11enemies in, 15enemy attacks in, 16enemy classes in, 65enemy movement in, 68–72font used in, 92fragment shader for, 158game controls for, 14, 32–33

game objects for, 17handling complex interactions

for, 26implementing Game Center

features in, 104–109implementing translations in,

160–162keeping score in, 94–96menu screen for, 46orthographic projection in, 44parent sprite class in, 154perspective in, 44player/enemy movement in, 16player vs. enemy shots in, 16scenes in, 32scoreboard for, 90shooting in, 16showing iAds in, 120sounds for, 18, 19, 85Sprite class for, 42–46types of enemies in, 64vertex shader for, 159vertices in, 37

Real Racing 2 game, 59, 123real-time strategy games, 10, 68rectangles, 37render buffers, 138rendering code, 140–142rendering fonts, xiii, 91–93retain count, 177Retina Display, 17revenue, advertising/product,

118–122, 124–128Rideout, Phillip, 184rotation, 45RTS games, 10, 68Ruby, 179Run Button, 23

sscaling, 45scene controllers, 32scenes

abstract class for, 34adding to dictionary, 52changing, 50–52defined, 32

190 indeX

examples of common, 32initializing, 52rendering, 36updating, 136where game stores, 97

scoreboard, 90, 91scores

adding to Game Center, 106filtering, 104storing, 106

scoring games, 90, 94–96screen space, 44second display feature, 123selectors, 50sending tweets, 110–114sendTweet code, 165setHidden method, 121setter methods, 173setupGL method, 25setup method, 150, 165shader.fsh file, 25, 26, 148Shader Language, 25, 29shaders

applying, 158–162compiling, 143creating, 43, 148–151deleting, 26–28linking, 143–151purpose of, 25

shader.vsh file, 25, 26, 148shading effects, 43–44sharedGameController variable, 36shared resources, 33shooter games, 68shooting missiles, 16, 79, 95. See also

missilesSimulator, 23Simulator, iOS, xii, 23single-screen action games, 10, 11. See

also Raiderssingletons, 33, 35Single View Application option, 134sketches, xiii, 10, 12SlidingDoor class, 32slope-of-line formula, 70, 71Smalltalk, 169

social features, 101–115Game Center integration, 102–109leaderboards, 104–109Twitter updates, 110–114

social gaming network, 102–103social networks, 101sound design, 12sound editor, xiiisound effects, 18–19, 84–86SoundEffects class, 85, 86Space Invaders, 4spherical bounds, 77spot effects, 85sprite arrays, clearing, 97Sprite class, 42–46, 158. See also

spritesSprite.h file, 154Sprite.m file, 39, 154, 159, 160, 161sprites. See also enemy sprites

changing header for, 155checking bounds for, 60, 76–77copying vs. assigning, 93creating, 17defined, 4drawing, 37–38movement patterns for, 68moving, 160player vs. enemy, 53putting in action, 39–46rendering, 45–46size considerations, 17sources of free, 18transforming, 155

sprite sheets, 5sprite velocity, 69square brackets, 170squares, 37, 38squareVertices array, 150Stahler, Wendy, 185startRun method, 64stock graphics, 18StoreKit framework, 124Storyboard feature, 24, 25Storyboard file, 25strafingFinished method, 81strafing runs, 64, 65, 68–69strategy games, 7, 68streaming audio/video, 123

strings, 175structs, 41(s,t) system, 40Supporting Files group, 163SynthesizeSingleton.h file, 35System Sound Services, 85

ttaking-ownership technique, 177tapAction method, 50, 51target objects, 51template app, 25, 26template, OpenGL ES, 134, 151terminology, 32–33Test Account, iTunes Connect, 124texCoordIn attribute, 159texCoords array, 159–160texture coordinates, 43texture coordinate system, 40texture mapping, 38, 39–40, 43textures

calculating pixels in, 78copying vs. assigning, 93loading in GLES2, 156–157mapping (See texture mapping)OpenGL ES limitations on, 38POT vs. NPOT, 156, 163reading, 156–157rendering, 158

three-dimensional games. See 3D games

threshold level, acceleration, 55tilt-based control, 54–55touch-based control, 53, 58, 162touchesBegan method, 56touchesEnded method, 51, 56, 57touchesMoved method, 53touchPoint parameter, 50touchscreen, 14transformation matrix, 44, 46transformations, 45, 155, 161, 167translations, 45, 160–162translation variable, 160transparent backgrounds, 43triangles, 37–38TrueType fonts, 91TV Out technology, 59

indeX 191

tweets, sending, 110–114Twitter, 110–114

account setup, 110and iOS versions, 165sending tweets to, 111–114

two-dimensional games. See 2D gamesTWRequest method, 114TWTweetComposeViewController,

110, 111–112

UUIAccelerometerDelegate method, 54UIKit View Controller, 104UIView, 136UIViewController, 51, 107Unity game engine, 5update method, 25updateScene method, 34updateTransforms method, 44, 66updateWorld method, 35usage rights, 18Use Automatic Reference Counting

option, 134UV mapping, 40(u,v) system, 40

vvanishing point, 44vector space, 44velocity, sprite, 69vertex arrays, 41, 160vertex data, 25, 37, 41vertex shader, 159–160, 161_vertex variables, 26vertices, 37, 150. See also vertex datavideo streaming, 123ViewController

changing header file for, 163displaying ads in, 118–119editing, 163–165files, 24, 25and inheritance, 51and redrawing screens, 142sending tweets without, 113–114vs. GameController, 36vs. Sprite class, 158

viewDidLoad method, 25view modes, 12–13virtual joystick control, 55–58

WWAV files, 19, 85weapons, 4winning levels, 96

xXcode

creating new projects in, 22, 134examining specific files in, 24–25files pane, 34iOS Simulator, 23purpose of, xiitemplate, 134, 151

.xib files, 24, 25x plane, 160x,y points, 37

y“you win” message, 96y plane, 160

zz plane, 160

192 indeX