Unity in Action, Third Edition by Joseph Hocking PDF

Title Unity in Action, Third Edition by Joseph Hocking
Author Azizi Othman
Pages 418
File Size 20.1 MB
File Type PDF
Total Downloads 220
Total Views 676

Summary

THIRD EDITION Multiplatform game development in C# Joseph Hocking Foreword by Jesse Schell MANNING Learn a laundry list of techniques for building your own games: 3D camera control • Chapter 2 Raycasting • Chapter 3 Displaying 2D graphics • Chapter 5 2D physics • Chapter 6 Put a GUI on your game • C...


Description

THIRD EDITION

Multiplatform game development in C#

Joseph Hocking Foreword by Jesse Schell

MANNING

Learn a laundry list of techniques for building your own games: 3D camera control

• Chapter 2

Raycasting

• Chapter 3

Displaying 2D graphics

• Chapter 5

2D physics

• Chapter 6

Put a GUI on your game

• Chapter 7

Manage the player's inventory

• Chapter 9

Make HTTP requests

• Chapter 10

Sound effects and music

• Chapter 11

Deploy to desktop, web, or mobile

• Chapter 13

And much, much more!

Praise for earlier editions of Unity in Action Step-by-step examples and clear prose make this the go-to book for Unity! —Victor M. Perez, Software developer Everything you need to know about Unity in one single resource. —Dan Kacenjar, Cornerstone Software Start creating your own game prototypes in no time. —David Torrubia Iñigo, Fintonic The text is clear and concise, and the examples are outstanding. —Dan Kacenjar, Sr., Wolters Kluwer All the roadblocks evaporated, and I took my game from concept to build in short order. —Philip Taffet, SOHOsoft Joe Hocking wastes none of your time and gets you coding fast. —Jesse Schell, author of The Art of Game Design I’ve wanted to program in Unity for a long time, and this book has given me the confidence to do so. —Robin Dewson, Schroders Gets you up and running in no time. —Sergio Arbeo, codecantor

Unity in Action, Third Edition MULTIPLATFORM GAME DEVELOPMENT IN C#

JOSEPH HOCKING FOREWORD BY JESSE SCHELL

MANNING SHELTER ISLAND

For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: [email protected] ©2022 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964

ISBN 9781617299339 Printed in the United States of America

Development editor: Review editor: Production editor: Copy editor: Proofreader: Typesetter: Cover designer:

Becky Whitney Mihaela Batinić Deirdre S. Hiam Sharon Wilkey Jason Everett Gordan Salinovic Marija Tudor

brief contents PART 1 FIRST STEPS .....................................................................1 1 2 3 4

■ ■ ■ ■

Getting to know Unity 3 Building a demo that puts you in 3D space 23 Adding enemies and projectiles to the 3D game Developing graphics for your game 75

50

PART 2 GETTING COMFORTABLE ................................................101 5 6 7 8 9



■ ■ ■



Building a Memory game using Unity’s 2D functionality 103 Creating a basic 2D platformer 128 Putting a GUI onto a game 147 Creating a third-person 3D game: Player movement and animation 171 Adding interactive devices and items within the game 200

v

vi

BRIEF CONTENTS

PART 3 STRONG FINISH ............................................................227 10 11 12 13

■ ■ ■ ■

Connecting your game to the internet 229 Playing audio: Sound effects and music 257 Putting the parts together into a complete game Deploying your game to players’ devices 314

282

contents foreword xv preface xvii acknowledgments xix about this book xxi about the author xxv about the cover illustration

xxvi

PART 1 FIRST STEPS ...........................................................1

1

Getting to know Unity 1.1

3

Why is Unity so great? 4 Unity’s strengths and advantages 4 Example games built with Unity 7

1.2

How to use Unity



Downsides to be aware of

10

Scene view, Game view, and the Toolbar 12 The mouse and keyboard 14 The Hierarchy view and the Inspector panel 15 The Project and Console tabs 16 ■



1.3

Getting up and running with Unity programming 16 Running code in Unity: Script components 17 Using Visual Studio, the included IDE 18 Printing to the console: Hello World! 19 ■



vii

6

viii

CONTENTS

2

Building a demo that puts you in 3D space 2.1

Before you start . . . Planning the project space 25

2.2

23

24 24



Understanding 3D coordinate

Begin the project: Place objects in the scene 27 The scenery: Floor, outer walls, and inner walls 28 Lights and cameras 30 The player’s collider and viewpoint 32 ■



2.3

Make things move: A script that applies transforms

33

Visualizing how movement is programmed 33 Writing code to implement the diagram 34 Understanding local vs. global coordinate space 35 ■



2.4

Script component for looking around: MouseLook

37

Horizontal rotation that tracks mouse movement 38 Vertical rotation with limits 39 Horizontal and vertical rotation at the same time 41 ■



2.5

Keyboard input component: First-person controls

44

Responding to keypresses 44 Setting a rate of movement independent of the computer’s speed 45 Moving the CharacterController for collision detection 46 Adjusting components for walking instead of flying 47 ■





3

Adding enemies and projectiles to the 3D game 3.1

Shooting via raycasts

50

51

What is raycasting? 51 Using the ScreenPointToRay command for shooting 52 Adding visual indicators for aiming and hits 54 ■



3.2

Scripting reactive targets Determining what was hit hit 58

3.3

Basic wandering AI

57 57



Alerting the target that it was

60

Diagramming how basic AI works 60 “Seeing” obstacles with a raycast 61 Tracking the character’s state 62 ■



3.4

Spawning enemy prefabs

64

What is a prefab? 64 Creating the enemy prefab 65 Instantiating from an invisible SceneController 65 ■

3.5

Shooting by instantiating objects

68

Creating the projectile prefab 68 Shooting the projectile and colliding with a target 70 Damaging the player 73 ■



ix

CONTENTS

4

Developing graphics for your game

75

4.1

Understanding art assets

76

4.2

Building basic 3D scenery: Whiteboxing 78 Whiteboxing explained 79 Drawing a floor plan for the level 79 Laying out primitives according to the plan 80 ■



4.3

Texturing the scene with 2D images Choosing a file format 83 Applying the image 85

4.4

84

Generating sky visuals by using texture images

87

What is a skybox?

4.5

87



Creating a new skybox material

Working with custom 3D models Which file format to choose? model 92

4.6

82

Importing an image file



91



88

90

Exporting and importing the

Creating effects by using particle systems

95

Adjusting parameters on the default effect 96 Applying a new texture for fire 98 Attaching particle effects to 3D objects 99 ■



PART 2 GETTING COMFORTABLE ......................................101

5

Building a Memory game using Unity’s 2D functionality 5.1

Setting up everything for 2D graphics

103

104

Preparing the project 105 Displaying 2D images (aka sprites) 107 Switching the camera to 2D mode 108 ■



5.2

Building a card object and making it react to clicks Building the object out of sprites 110 Revealing the card on a click 112

5.3

Displaying the various card images



Mouse input code

110 111

113

Loading images programmatically 113 Setting the image from an invisible SceneController 114 Instantiating a grid of cards 116 Shuffling the cards 118 ■





5.4

Making and scoring matches

119

Storing and comparing revealed cards 120 Hiding mismatched cards 120 Text display for the score 121 ■



5.5

Restart button

123

Programming a UIButton component by using SendMessage Calling LoadScene from SceneController 126

124

x

CONTENTS

6

Creating a basic 2D platformer 128 6.1

Setting up the graphics Placing the scenery

6.2

129

129 ■

133



Colliding with the block

Playing the sprite’s animation

Adding the ability to jump Falling from gravity 137 Detecting the ground 139

6.5



134

134

Explaining the Mecanim animation system animations from code 136

6.4

130

Moving the player left and right 132 Writing keyboard controls

6.3

Importing sprite sheets

134

Triggering



137 Applying an upward impulse

Additional features for a platform game

138

140

Unusual floors: Slopes and one-way platforms 140 moving platforms 142 Camera control 145



Implementing



7

Putting a GUI onto a game 7.1

147

Before you start writing code . . .

149

Immediate mode GUI or advanced 2D interface? the layout 150 Importing UI images 151

149

Planning





7.2

Setting up the GUI display

151

Creating a canvas for the interface 151 Buttons, images, and text labels 153 Controlling the position of UI elements 156 ■



7.3

Programming interactivity in the UI

157

Programming an invisible UIController 158 Creating a pop-up window 160 Setting values using sliders and input fields 163 ■



7.4

Updating the game by responding to events Integrating an event system events from the scene 167 from the HUD 168

8

166

166 Broadcasting and listening for Broadcasting and listening for events ■



Creating a third-person 3D game: Player movement and animation 171 8.1

Adjusting the camera view for third-person

173

Importing a character to look at 174 Adding shadows to the scene 175 Orbiting the camera around the player character 177 ■



8.2

Programming camera-relative movement controls Rotating the character to face movement direction forward in that direction 183

180



180 Moving

xi

CONTENTS

8.3

Implementing the jump action

184

Applying vertical speed and acceleration 185 Modifying the ground detection to handle edges and slopes 186 ■

8.4

Setting up animations on the player character 190 Defining animation clips in the imported model 192 Creating the animator controller for these animations 194 Writing code that operates the animator 197 ■



9

Adding interactive devices and items within the game 9.1

Creating doors and other devices

200

201

Doors that open and close on a keypress 201 Checking distance and facing before opening the door 203 Operating a colorchanging monitor 205 ■



9.2

Interacting with objects by bumping into them

206

Colliding with physics-enabled obstacles 206 Operating the door with a trigger object 207 Collecting items scattered around the level 210 ■



9.3

Managing inventory data and game state 212 Setting up player and inventory managers 212 Programming the game managers 214 Storing inventory in a collection object: List vs. Dictionary 217 ■



9.4

Inventory UI for using and equipping items

220

Displaying inventory items in the UI 220 Equipping a key to use on locked doors 223 Restoring the player’s health by consuming health packs 224 ■



PART 3 STRONG FINISH ..................................................227

10

Connecting your game to the internet 10.1

Creating an outdoor scene

229

231

Generating sky visuals by using a skybox 231 atmosphere that’s controlled by code 232

10.2



Setting up an

Downloading weather data from an internet service 235 Requesting HTTP data using coroutines 238 Parsing XML 242 Parsing JSON 243 Affecting the scene based on weather data 246 ■



10.3



Adding a networked billboard 247 Loading images from the internet 247 Displaying images on the billboard 250 Caching the downloaded image for reuse 251 ■



xii

CONTENTS

10.4

Posting data to a web server 253 Tracking current weather: Sending post requests code in PHP 255

11

254



Server-side

Playing audio: Sound effects and music 257 11.1

Importing sound effects Supported file formats

11.2

Playing sound effects

258

258



Importing audio files

260

261

Explaining what’s involved: Audio clip vs. source vs. listener 261 Assigning a looping sound 263 Triggering sound effects from code 264 ■

11.3

Using the audio control interface

265

Setting up the central AudioManager 265 UI 267 Playing UI sounds 271



Volume control



11.4

Adding background music 272 Playing music loops 272 Controlling music volume separately 276 Fading between songs 278 ■



12

Putting the parts together into a complete game 12.1

282

Building an action RPG by repurposing projects

283

Assembling assets and code from multiple projects 284 Programming point-and-click controls: Movement and devices Replacing the old GUI with a new interface 292

12.2

Developing the overarching game structure

286

299

Controlling mission flow and multiple levels 299 Completing a level by reaching the exit 303 Losing the level when caught by enemies 305 ■



12.3

Handling the player’s progression through the game Saving and loading the player’s progress by completing three levels 311

13

Deploying your game to players’ devices 13.1

307



307

Beating the game

314

Start by building for the desktop: Windows, Mac, and Linux 317 Building the application 317 Adjusting player settings: Setting the game’s name and icon 318 Platform-dependent compilation 319 ■



13.2

Building for the web

321

Building the game embedded in a web page with JavaScript in the browser 322

321



Communicating

xiii

CONTENTS

13.3

Building for mobile: iOS and Android 325 Setting up the build tools 326 Developing plugins 332

13.4



Developing XR (both VR and AR) Supporting virtual reality headsets mobile Augmented Reality 342

afterword appendix appendix appendix appendix

A B C D

Texture compression 331

341

341 ■

AR Foundation for

349

Scene navigation and keyboard shortcuts 353 External tools used alongside Unity 356 Modeling a bench in Blender 360 Online learning resources 369 index

373

foreword I started programming games in 1982. It wasn’t easy. We had no internet. Resources were limited to a handful of mostly terrible books and magazines that offered fascinating but confusing code fragments, and as for game engines—well, there weren’t any! Coding games was a massive uphill battle. How I envy you, reader, holding the power of this book in your hands. The Unity engine has done so much to open game programming up to so many people. Unity has managed to strike an excellent balance by being a powerful, professional game engine that’s still affordable and approachable for someone just getting started. Approachable, that is, with the right guidance. I once spent time in a circus troupe run by a magician. He was kind enough to take me in and helped guide me toward becoming a good performer. “When you stand on a stage,” he pronounced, “you make a promise. And that promise is ‘I will not waste your time.’” What I love most about Unity in Action is the “action” part. Joe Hocking wastes none of your time and gets you coding fast—and not just nonsense code, but interesting code that you can understand and build from, because he knows you don’t just want to read his book, and you don’t just want to program his examples—you want to be coding your own game. And with his guidance, you’ll be able to do that sooner than you might expect....


Similar Free PDFs