Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Unity 4.x Game Development by Example Beginner's Guide
Unity 4.x Game Development by Example Beginner's Guide
Unity 4.x Game Development by Example Beginner's Guide
Ebook1,098 pages8 hours

Unity 4.x Game Development by Example Beginner's Guide

Rating: 3 out of 5 stars

3/5

()

Read preview

About this ebook

In Detail

Unity is one of the biggest game engines in the world, providing the user with a range of important tools that they need to bring their ideas into reality. Beginner game developers are optimistic, passionate, and ambitious, but that ambition can be dangerous! Too often, budding indie developers and hobbyists bite off more than they can chew. Games like Angry Birds, Cut the Rope, and Fruit Ninja are fun, simple games that have delighted players and delivered big profits to their creators. This is the perfect climate for new game developers to succeed by creating simple games with Unity, starting today.

This book teaches you the ins and outs of the unique Unity game engine interface. Clear and concise code examples written in both Unity Javascript and C# take you through the step-by-step process of building five small, functional games. With this understanding you can start making your own mark on the game industry!

With absolutely no programming or game development experience, you will learn how to build five simple games in Unity by following step-by-step instructions, peppered with amusing analogies and anecdotes from an experienced indie developer. Following a primer on simplifying your game ideas to that single "something" that keeps players coming back for more, dive into the Unity game engine by creating a simple bat-and-ball game. From there, you'll build a complete memory game using only the Unity GUI system. After building a 2.5D mouse avoider game, you'll learn how to re-skin the project to completely change the game's theme. Incorporating everything you've learned, you'll return to complete the bat-and-ball game by adding scoring, replay flow, sound effects, and animations. Finally, in the new bonus chapter, you'll program some simple AI (Artificial Intelligence) for a tic tac toe game.

"Unity 4.x Game Development by Example" is a fun and light-hearted exploration of one of the most powerful game engines on the market today. Find out what all the fuss is about by getting up to speed using this book!

Approach

This is a practical and light-hearted guide to get to grips with creating your first games, with easy-to-follow, step-by-step tutorials using the award winning Unity engine.

Who this book is for

If you’ve ever wanted to enter the world of independent game development but have no prior knowledge of programming or game development, then this is the book for you. Game developers transitioning from other tools like GameMaker and Flash will find this a useful tool to get them up to speed on the Unity engine, as will anyone who has never handled the Unity engine before.

LanguageEnglish
Release dateDec 26, 2012
ISBN9781849695275
Unity 4.x Game Development by Example Beginner's Guide
Author

Ryan Henson Creighton

Ryan Henson Creighton is a veteran game developer, and the founder of Untold Entertainment Inc. (http://www.untoldentertainment.com) where he creatively consults on games and applications. Untold Entertainment creates fantastically fun interactive experiences for players of all ages. Prior to founding Untold, Ryan worked as the Senior Game Developer at Canadian media conglomerate Corus Entertainment, where he created over fifty advergames and original properties for the YTV, Treehouse TV, and W networks. Ryan is the co-creator of Sissy's Magical Ponycorn Adventure, the game he authored with his then five-year-old daughter Cassandra. Ryan is the Vice President of the IGDA Toronto Chapter. He is also the author of the book that you are currently reading. When Ryan is not developing games, he's goofing off with his two little girls and his funloving wife in downtown Toronto.

Read more from Ryan Henson Creighton

Related to Unity 4.x Game Development by Example Beginner's Guide

Related ebooks

Programming For You

View More

Related articles

Reviews for Unity 4.x Game Development by Example Beginner's Guide

Rating: 3 out of 5 stars
3/5

1 rating0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Unity 4.x Game Development by Example Beginner's Guide - Ryan Henson Creighton

    Table of Contents

    Unity 4.x Game Development by Example Beginner's Guide

    Credits

    About the Author

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers and more

    Why Subscribe?

    Free Access for Packt account holders

    Preface

    A word about the third edition

    Your future as a game developer

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the color images of this book

    Downloading the example code

    Errata

    Piracy

    Questions

    1. That's One Fancy Hammer!

    Introducing Unity 3D

    The engine, the tool, and the all-weather tires

    Unity takes over the world

    Why choose Unity?

    Why burn this book and run away screaming?

    Browser-based 3D – welcome to the future

    Time for action – install the Unity Web Player

    Welcome to Unity 3D!

    What can I build with Unity?

    FusionFall

    Completely hammered

    Should we try to build FusionFall?

    Another option

    Off-Road Velociraptor Safari

    Fewer features, more promises

    Maybe we should build Off-Road Velociraptor Safari?

    I bent my Wooglie

    Big Fun Racing

    Diceworks

    Lovers in a Dangerous Spacetime

    Showcase Showdown

    Unity Technologies – Made with Unity page

    Kongregate

    The iOS App Store

    Walk before you can run (or double jump)

    There's no such thing as finished

    Stop! Hammer time

    Fight Some Angry Bots

    The wonders of technology!

    The Scene window

    The Game window

    The Hierarchy panel

    The Project panel

    The Inspector panel

    Heads Up?

    Layers and layout dropdowns

    Playback controls

    Scene controls

    Don't stop there – live a little!

    Summary

    Big ambition, tiny games

    2. Let's Start with the Sky

    That little lightbulb

    The siren song of 3D

    Features versus content

    A game with no features

    Mechanic versus skin

    Trapped in your own skin

    That singular piece of joy

    One percent inspiration

    Motherload

    Possible additional features:

    Heads up!

    Artillery Live!

    The skinny on multiplayer

    Bang for your buck

    Pong

    The mechanic that launched a thousand games

    Have a go hero – redesign your favorite games

    Toy or story

    Pop Quiz – finding that singular piece of joy

    Redefining the sky

    Summary

    Let's begin

    3. Game #1 – Ticker Taker

    Kick up a new Unity project

    Where did everything go?

    'Tis volley

    Keep the dream alive

    Slash and burn!

    The many faces of keep-up

    Creating the ball and the hitter

    Time for action – create the Ball

    What just happened – that's all there is to it?

    A ball by any other name

    Time for action – rename the Ball

    Origin story

    XYZ/RGB

    Time for action – move the Ball Into the Sky

    Time for action – shrink the Ball

    Time for action – save your scene

    Time for action – add the Paddle

    What's a Mesh?

    Poly wants to crack your game performance?

    Keeping yourself in the dark

    Time for action – add a light

    Time for action – move and rotate the light

    Have a go hero

    Extra credit

    Are you a luminary?

    Who turned out the lights?

    Darkness reigns

    Cameramania

    Time for action – test your game

    Let's get physical

    Add physics to your game

    Understanding the gravity of the situation

    More bounce to the ounce

    Time for action – make the Ball bouncy

    Have a go hero

    Summary

    Following the script

    4. Code Comfort

    What is code?

    Time for action – write your first Unity Script

    A leap of faith

    Lick it and stick it

    Disappear me!

    What just happened?

    It's all Greek to me

    You'll never go hungry again

    With great sandwich comes great responsibility

    Examining the code

    Time for action – find the Mesh Renderer component

    Time for action – make the ball re-appear

    Ding!

    Time for action – journey to the Unity Script Reference

    The Renderer class

    Have a go hero – pulling the wings off of flies

    What's another word for huh?

    It's been fun

    Time for action – unstick the Script

    Gone, but not forgotten

    Why code?

    Equip your baby bird

    Time for action – create a new MouseFollow Script

    What just happened?

    A capital idea

    Animating with code

    Time for action – animate the Paddle

    What just happened – what witchcraft is this?

    Why didn't the Paddle animate before?

    Pick a word – (almost) any word

    Screen coordinates versus World coordinates

    Move the Paddle

    Worst. Game. Ever.

    See the matrix

    Time for action – listen to the paddle

    A tiny bit o' math

    Tracking the numbers

    Futzing with the numbers

    Time for action – Log the New Number

    She's a-work!

    Somebody get me a bucket

    Time for action – declare a variable to store the Screen midpoint

    What just happened – we've gone too var

    Using all three dees

    Time for action – follow the y position of the mouse

    A keep-up game for robots

    Once more into the breach

    Time for action – re-visit the Unity Language Reference

    Our work here is done

    Time for action – add the sample code to your Script

    One final tweak

    What's a quaternion?

    Wait, what's a quaternion?

    WHAT THE HECK IS A QUATERNION??

    Educated guesses

    More on Slerp

    Right on target

    Have a go hero – time to break stuff

    Keep it up

    Beyond the game mechanic

    C# Addendum

    5. Game #2 – Robot Repair

    You'll totally flip

    A blank slate

    You're making a scene

    Time for action – set up two scenes

    No right answer

    Time for action – prepare the GUI

    The beat of your own drum

    Time for action – create and link a custom GUI skin

    What just happened?

    Time for action – create a button UI control

    What just happened?

    Have a go hero – no sense sitting around on your button

    Want font?

    Cover your assets

    Time for action – nix the mip-mapping

    Front and center

    Time for action – center the button

    What just happened – investigating the code

    The waiting game

    The easiest button to button

    To the game!

    Time for action – add both scenes to Build List

    Set the stage for robots

    Time for action – prepare the game scene

    The game plan

    Have some class!

    Time for action – store the essentials

    A matter of great import

    Building a better bucket

    How big is your locker?

    Start me up

    Going loopy

    The anatomy of a loop

    To nest is best

    Seeing is believing

    Time for action – create an area to store the grid

    Have a go hero – don't take my word for it!

    Build that grid

    What just happened – grokking the code

    Now you're playing with power!

    C# addendum

    6. Game #2 – Robot Repair Part 2

    From zero to game in one chapter

    Finding your center

    Time for action – centering the game grid vertically

    What just happened?

    Time for action – centering the game grid horizontally

    What just happened – coding like a ninja

    Down to the nitty griddy

    Do the random card shuffle

    Time for action – preparing to build the deck

    Let's break some robots

    Time for action – building the deck

    What just happened – dissecting the bits

    Time for action – modifying the img argument

    What just happened?

    What exactly is this?

    Have a go hero – grokketh-thou Random.Range()?

    Random reigns supreme

    Second dragon down

    Time to totally flip

    Time for action – making the cards two-sided

    Time for action – building the card-flipping function

    Time for action – building the card-flipping function

    What just happened – dissecting the flip

    Pumpkin eater

    What just happened?

    Stabby McDragonpoker rides again

    Game and match

    Time for action – ID the cards

    What just happened?

    Time for action – comparing the IDs

    What just happened?

    On to the final boss

    Endgame

    Time for action – checking for victory

    What just happened?

    Have a go hero – extra credit

    Endgame

    Bring. It. On.

    C# Addendum

    7. Don't Be a Clock Blocker

    Apply pressure

    Time for action – preparing the Clock Script

    Time for more action – preparing the clock text

    Still time for action – changing the clock text color

    Time for action rides again – creating Font Texture and Material

    Time for action – what's with the tiny font?

    What just happened – was that seriously magic?

    Time for action – preparing the clock code

    What just happened – that's a whole lotta nothing

    Time for action – creating the countdown logic

    Time for action – displaying the time on-screen

    What just happened – what about that terrifying code?

    Picture it

    Time for action – grabbing the picture clock graphics

    What just happened – you can do that?

    Time for action – Flex those GUI muscles

    What just happened – how does it work?

    The incredible shrinking clock

    Keep your fork – there's pie!

    Pop quiz – how do we build it?

    How they did it

    Time for action – rigging up the textures

    Time for action – writing the pie chart script

    What just happened?

    Time for action – commencing operation pie clock

    What just happened – explaining away the loose ends

    Time for action – positioning and scaling the clock

    Have a go hero – rock out with your clock out

    Unfinished business

    C# Addendum

    8. Hearty Har Har

    Welcome to Snoozeville

    Model behavior

    Time for action – exploring the models

    Time for action – hands up!

    What just happened – size matters

    Time for action – changing the FBX import scale settings

    Time for action – making the mesh colliders convex

    Time for action – making the hands and tray follow the mouse

    What just happened – monkey see, monkey do

    Time for action – getting your heart on

    Time for action – ditching the Ball and Paddle

    What just happened – bypass the aorta

    Time for action – material witness

    What just happened – understanding Materials

    Have a go hero – adding materials to the other models

    This just in – this game blows

    Time for action – multiple erections

    Time for action – creating a font texture

    Time for action – create the HeartBounce script

    What just happened – charting a collision course

    Time for action – tagging the tray

    Time for action – tweaking the bounce

    What just happened – storing velocity

    Time for action – keeping track of the bounces

    Time for action – adding the lose condition

    What just happened – understanding the code

    Time for action – adding the Play Again button

    What just happened?

    Ticker taken

    C# Addendum

    9. Game #3 – The Break-Up

    Time for action – bombs away!

    Time for action – poke those particles

    Time for action – creating a spark material

    Have a go hero – time to ignite your creative spark

    Time for action – prefabulous

    What just happened – what's a Prefab?

    Time for action – lights, camera, and apartment

    Time for action – adding the character

    Time for action – registering the animations

    Time for action – scripting the character

    What just happened – stepping through the step code

    Time for action – open the pod bay door, Hal

    Time for action – collision-enable the character

    Time for action – apocalypse now?

    Time for action – go boom

    Time for action – kill kill murder die

    Time for action – the point of impact

    Time for action – hook up the explosion

    Summary

    C# addendum

    10. Game #3 – The Break-Up Part 2

    Time for action – amass some glass

    Time for action – create a particle system

    What just happened – getting smashed

    Time for action – make it edgier!

    What just happened – I fall to pieces

    Time for action – contain the explosion

    What just happened – duped?

    Time for action – let's get lazy

    What just happened – FallingObject: The PuppetMaster

    Very variable?

    Terminal velocity is a myth – bombs fall faster

    What just happened – when game objects collide?

    Time for action – tag the objects

    Time for action – write the collision detection code

    Time for action – animation interrupts

    What just happened – the impenetrable stare

    Time for action – add facial explosions

    What just happened – raindrops keep 'sploding on my head

    Time for action – make some noise

    Time for action – add sounds to FallingObject

    Silent 'Splosion

    What's the catch?

    Have a go hero – sound off

    Time for action – mix it up a bit

    Have a go hero – filling in the gaps

    Summary

    C# Addendum

    11. Game #4 – Shoot the Moon

    Time for action – duplicate your game project

    Time for action – space the shooter up a bit

    Time for action – enter the hero

    Time for action – it's a hit!

    Time for action – bring on the bad guys

    Time for action – do some housekeeping

    Time for action – fixing the fall

    Time for action – tweak the hero

    What just happened – hooray for lazy!

    Time for action – give up the func

    Time for action – itchy trigger finger

    Time for action – futurize the bullet

    Time for action – building Halo

    Time for action – fire!

    Time for action – code do-si-do

    What just happened – eat lead

    Time for action – the maaagic of aaaarguments

    Time for action – add the most important part of any space shooter

    Last year's model

    Have a go hero – filling in the empty space

    Summary

    C# Addendum

    12. Game #5 – Kisses 'n' Hugs

    Computers that think

    Time for action – haul in the hallway

    Time for action – hash it out

    One Script to rule them all

    Time for action – it's hip to be square

    What just happened – find and click

    Squaring the Square

    Time for action – now you see it...

    Family values

    Time for action – X marks the spot

    Time for action – boy O boy

    Time for action – bottoming out

    Here comes the drop

    What just happened – to collide or not to collide?

    Time for action – +9 accuracy

    Time for action – solve for X

    What just happened – lockdown

    Time for action – it takes two to Tic Tac Toe

    What just happened – alternating between players

    Time for action – designer to player. Come in, player.

    What just happened – prompt service

    Slowly building to a climax

    Have a go hero – think it through

    Read after thinking

    What just happened – building a more complex lock

    On deaf ears

    Time for action – pretty maids all in a row

    What just happened – order!

    Winner is coming

    Codesplosion

    Need-to-know basis

    Need-to-know basis

    Clean-up on aisle code

    What just happened – vending machine

    Shave and a haircut

    What just happened – hunting for a win

    Time for action – check for a win

    Sore loser

    Time for action – notify the winner

    Time for action – you win. Now what?

    Have a go hero – draw, pardner

    Nice moves

    Time for action – the final bug

    All done but for the shouting

    C# addendum

    13. AI Programming and World Domination

    Take it away, computer

    Time for action – add computer control

    Herpa derp derp

    What just happened – making a list, checking it twice

    Unpacking the code

    Time for action – code consolidation

    Tic Tac Toe at the speed of light

    Sore loser

    Click-spamming for fun and profit

    Artificial stupidity

    Have a go hero – solve Tic Tac Toe

    Time for action – winning is everything

    It's a trap!

    The leftovers

    Time for action – pseu pseu pseudocode

    What just happened – stepping through the strategy

    Time for action – begin at the end

    Time for action – the final four

    Code one, get one free

    Have a go hero - stump the author

    The actual intelligence behind artificial intelligence

    Time for action – score!

    What just happened – the search is on

    Shut your trap

    Detecting the tri-corner trap

    Time for action – to catch a competitor

    What just happened – I'm running out of trap puns

    Perfection Horrible, horrible perfection.

    Time for action – programming fallibility

    What just happened – roll for initiative

    Turning it up to Smart

    Code encore

    Summary

    More hospitality

    C# addendum

    14. Action!

    Open heart surgery

    Time for action – haul in the hallway

    Time for action – meet me at camera two

    Time for action – adjust Main Camera

    Time for action – deck the halls

    Time for action – turn on the lights

    Time for action – set up the camera rig

    Time for action – animate the bouncer

    What just happened – red and raging

    Time for action – I like to move it move it

    Have a go hero – bounce your brains out

    Time for action – animate the runner

    What just happened – holy hospital rampage, Batman!

    Time for action – how to handle Nurse Slipperfoot

    Time for action – you spin me right round

    Have a go hero – give Robo-Nurse a soul

    Have a go hero – use your new-found powers for good

    Time for action – deploy your game

    Time to grow

    Beyond the book

    A. Appendix

    Online resources

    Offline resources

    Free development tools

    Graphics

    Sound

    The Unity Asset Store

    Game portals

    Index

    Unity 4.x Game Development by Example Beginner's Guide


    Unity 4.x Game Development by Example Beginner's Guide

    Copyright © 2013 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: September 2010

    Second edition: September 2011

    Third edition: December 2013

    Production Reference: 1191213

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-84969-526-8

    www.packtpub.com

    Cover Image by Dan John Cox (<http://danjohncox.tumblr.com/>)

    Credits

    Author

    Ryan Henson Creighton

    Reviewers

    Trond Abusdal

    Huzaifa Arab

    John Hutchinson

    Wei Wang

    Acquisition Editors

    Wilson D'souza

    Mary Jasmine Nadar

    Owen Roberts

    Lead Technical Editors

    Owen Roberts

    Poonam Jain

    Technical Editors

    Tanvi Bhatt

    Akashdeep Kundu

    Edwin Moses

    Nikhil Potdukhe

    Tarunveer Shetty

    Faisal Siddiqui

    Sonali Vernekar

    Project Coordinator

    Venitha Cutinho

    Proofreaders

    Elinor Perry-Smith

    Mario Cecere

    Bridget Braund

    Indexers

    Mariammal Chettiyar

    Mehreen Deshmukh

    Rekha Nair

    Tejal Soni

    Graphics

    Sheetal Aute

    Production Coordinator

    Nitesh Thakur

    Cover Work

    Nitesh Thakur

    About the Author

    Ryan Henson Creighton is a veteran game developer, and the founder of Untold Entertainment Inc. (http://www.untoldentertainment.com) where he creatively consults on games and applications. Untold Entertainment creates fantastically fun interactive experiences for players of all ages. Prior to founding Untold, Ryan worked as the Senior Game Developer at Canadian media conglomerate Corus Entertainment, where he created over fifty advergames and original properties for the YTV, Treehouse TV, and W networks. Ryan is the co-creator of Sissy's Magical Ponycorn Adventure, the game he authored with his then five-year-old daughter Cassandra. Ryan is the Vice President of the IGDA Toronto Chapter. He is also the author of the book that you are currently reading.

    When Ryan is not developing games, he's goofing off with his two little girls and his fun-loving wife in downtown Toronto.

    Big thanks to Cheryl, Cassandra, and Isabel for their love, their support, and their cinnamon rolls. Thanks to Jean-Guy Niquet for introducing me to Unity; to Jim McMajorSupporter McGinley for help with the book outline and ongoing mentorship; to the technical reviewers and Packt Publishing staff for letting me leave a few jokes in the book; and to David Barnes, for having such a great sense of humor in the first place. Special thanks to Michael Garforth and friends from the #unity3d IRC channel on Freenode. I also want to thank Mom, God, and all the usual suspects.

    About the Reviewers

    Trond Abusdal, though having been interested in computers since his parents bought him and his brother a C64 in the early 90s, he first got into programming years later when writing a modification for Quake2 with a childhood friend.

    This interest lead to a bachelor's degree in Computer Science in 2006, after which he started working for TerraVision, a company using game technologies as a tool for education and visualization. In 2008, he first got introduced to Unity, which is still his main game development tool, although knowledge of other technologies and tools often come in handy.

    Since 2010, he is a programmer and more recently a partner at Rock Pocket Games, which makes games for a variety of different platforms, both client projects and internal projects.

    Huzaifa Arab is a Game Designer by choice and a Game Programmer by need. He has been playing games since young age, which progressed to Modding/Map-making/Scripting, when he realized that some games could be a whole lot more fun if he could put his own twist in them. And so, his hobby became a professional career choice after formally graduating from DSK Supinfogame, India (where his team won the prestigious Square Enix Game Dev Competition). After a year of freelance Game Development, he currently works at Tiny Mogul Games, India, as a Principal Game Designer.

    He loves to connect with people interested in Human Computer Interface, Game Engines/VR Tech, Game Design in Education, and Instrumental music. You can drop him a line at <arabhuzaifa@gmail.com>.

    I would like to thank Packt Publishing for giving me an opportunity to review a book on Unity 3D, a technology I am so passionate about. I would like to thank my best friend Angad for recommending me to Packt Publishing and I would like to thank my family and co-workers/friends for their support as I took time out to review such a wonderful book.

    John Hutchinson is the founder of Rubber Ducky Games, an independent game development studio based in California.

    In addition to being an exceptional programmer in multiple languages and frameworks, he is an experienced graphic designer, talented game system architect and gets excited about experience-focused design (and rubber duckies).

    He is especially interested in games which push the boundaries of twitch-reflex response, explore human emotion, or leverage the interactive medium for more powerful learning experiences.

    He is currently working with Making Friends Inc. as Lead Engineer and as part of the core design team, to deliver a game intent on teaching kids on the Autism-Asperger's spectrum valuable social skills.

    When his face isn't glued to a computer screen he likes to play with his kids, explore board game design, and read technical books like this one.

    Thanks to my brothers, for providing feedback (and teaching me some things about games). To my sister, for making me feel like a hero (not a robot). To my parents, for teaching me to be caring and to work my butt off. And to my kids, for just being you. I love you all more than words can express.

    Wei Wang made his first iOS casual game with Unity 3D in his college time, which got big success with more than 5 million downloads world-wide. Since then, he has discovered it's a great thing to make great games. After earning his master's degree from Tsinghua University (one of the best universities in China), he joined a game company in Japan and now he is trying to create interesting games with Unity 3D.

    Right now, he is a skilled engineer and always eager to learn more. He now lives in Kawasaki with his wife. You can know more about him from his project's page http://project.onevcat.com or find him on his blog http://onevcat.com (Chinese). You can also follow him on twitter @onevcat.

    www.PacktPub.com

    Support files, eBooks, discount offers and more

    You might want to visit www.PacktPub.com for support files and downloads related to your book.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    http://PacktLib.PacktPub.com

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

    Why Subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print and bookmark content

    On demand and accessible via web browser

    Free Access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

    Preface

    A word about the third edition

    As I sit here in my luxurious velvet smoking jacket, taking a long draw on a pipe, and admiring the various stuffed hunting trophies around the room in an attitude of quiet contemplation, it dawns on me that I don't smoke or advocate sport-hunting, and that I have no idea what I'm doing in this room. The jacket, however, is quite nice. I think I'll keep it.

    It's wonderful to see that this book, one of the very first instructional guides about Unity 3D on the market, has withstood both the test of time, and Unity Technologies' relentless release schedule. Owing to the rapid pace of technology, many things have changed in a few short years. C# has largely overtaken UnityScript as a preferred language; to that end, all of the code in the book has been supplemented with a C# translation, including notes on how to perform that translation yourself for past and future projects.

    In the time since the first edition, computers have increasingly become our evil, dominating overlords. With that in mind, the third edition includes two bonus chapters that teach you how to build a two-player game, and then how to program the computer to act as the merciless second player who never loses. That chapter also contains information on how to make the computer player lose, which I present as secret codified data to be used by the resistance movement during the inevitable machine uprising. Stay ever vigilant!

    Your future as a game developer

    Game Developer has rapidly replaced firetruck as the number one thing that kids want to be when they grow up. Gone are the days when aspiring developers needed a university education, a stack of punch cards, and a room-sized computer to program a simple game. With digital distribution and the availability of inexpensive (or free) game development tools like Unity 3D, the democratization of game development is well underway.

    But just as becoming a firetruck is fraught with peril, so too is game development. Too often, aspiring developers underestimate the sheer enormity of the multidisciplinary task ahead of them. They bite off far more than they can chew, and eventually drift away from their game development dreams to become lawyers or dental hygienists. It's tragic. This book bridges the gap between I wanna make games! and I just made a bunch of games! by focusing on small, simple projects that you can complete before you reach the bottom of a bag of corn chips.

    What this book covers

    Chapter 1, That's One Fancy Hammer!, introduces you to Unity 3D—an amazing game engine and game authoring tool that enables you to create games and deploy them to a number of different devices. You'll play a number of browser-based Unity 3D games to get a sense of what the engine can handle, from a massively-multiplayer online game all the way down to a simple kart racer. You'll download and install your own copy of Unity 3D, and mess around with one of the demos that ships with the product.

    Chapter 2, Let's Start with the Sky, explores the difference between a game's skin and its mechanic. Using examples from video game history, including Worms, Mario Tennis, and Scorched Earth, we'll uncover the small, singular piece of joy upon which more complicated and impressive games are based. By concentrating on the building blocks of video games, we'll learn how to distil an unwieldy behemoth of a game concept down to a manageable starter project.

    Chapter 3, Game #1 – Ticker Taker, puts you in the pilot seat of your first Unity 3D game project. We'll explore the Unity environment and learn how to create and place primitives, add Components like Physic Materials and rigidbodies, and make a ball bounce on a paddle using Unity's built-in physics engine without ever breaking a sweat.

    Chapter 4, Code Comfort, continues the keep-up game project by gently introducing scripting. Just by writing a few simple, thoroughly-explained lines of code, you can make the paddle follow the mouse around the screen to add some interactivity to the game. This chapter includes a crash course in game scripting that will renew your excitement for programming where high school computer classes may have failed you.

    Chapter 5, Game #2 – Robot Repair, introduces an often-overlooked aspect of game development—front-of-house User Interface design—the buttons, logos, screens, dials, bars, and sliders that sit in front of your game—is a complete discipline unto itself. Unity 3D includes a very meaty Graphical User Interface system that allows you to create controls and fiddly bits to usher your players through your game. We'll explore this system, and start building a complete two-dimensional game with it! By the end of this chapter, you'll be halfway to completing Robot Repair, a colorful matching game with a twist.

    Chapter 6, Game #2 – Robot Repair Part 2, picks up where the last chapter left off. We'll add interactivity to our GUI-based game, and add important tools to our game development tool belt, including drawing random numbers and limiting player control. When you're finished with this chapter, you'll have a completely playable game using only the Unity GUI system, and you'll have enough initial knowledge to explore the system yourself to create new control schemes for your games.

    Chapter 7, Don't Be a Clock Blocker, is a standalone chapter that shows you how to build three different game clocks—a number-based clock, a depleting bar clock, and a cool pie wedge clock, all of which use the same underlying code. You can then add one of these clocks to any of the game projects in this book, or reuse the code in a game of your own.

    Chapter 8, Hearty Har Har, revisits the keep-up game from earlier chapters and replaces the simple primitives with 3D models. You'll learn how to create materials and apply them to models that you import from external art packages. You'll also learn how to detect collisions between game objects, and how to print score results to the screen. By the end of this chapter, you'll be well on your way to building Ticker Taker—a game where you bounce a still-beating human heart on a hospital dinner tray in a mad dash for the transplant ward!

    Chapter 9, Game #3 – The Break-Up, is a wild ride through Unity's built-in particle system that enables you to create effects like smoke, fire, water, explosions, and magic. We'll learn how to add sparks and explosions to a 3D bomb model, and how to use scripting to play and stop animations on a 3D character. You'll need to know this stuff to complete The Break-Up—a catch game that has your character grabbing falling beer steins and dodging explosives tossed out the window by his jilted girlfriend.

    Chapter 10, Game #3 – The Break-Up Part 2, completes The Break-Up game from the previous chapter. You'll learn how to reuse scripts on multiple different game objects, and how to build Prefabs, which enable you to modify a whole army of objects with a single click. You'll also learn to add sound effects to your games for a much more engaging experience.

    Chapter 11, Game #4 – Shoot the Moon, fulfills the promise of Chapter 2, Let's Start with the Sky, by taking you through a re-skin exercise on The Break-Up. By swapping out a few models, changing the background, and adding a shooting mechanic, you'll turn a game about catching beer steins on terra firma into an action-packed space shooter! In this chapter, you'll learn how to set up a two-camera composite shot, how to use code to animate game objects, and how to re-jig your code to save time and effort.

    Chapter 12, Game #5 – Kisses 'n' Hugs, teaches you to build a two-player 3D Tic Tac Toe game entirely within the Unity 3D game authoring tool. You'll learn about writing return values for your custom functions, and using 3D objects to build an essentially 2D game. This simple strategy game forms the basis for the following chapter.

    Chapter 13, AI Programming and World Domination, steps you through the process of developing an artificial intelligence program, enabling your computer to win at Tic Tac Toe. From there, you'll modify the terrifyingly perfect AI algorithm so that it randomly makes mistakes, and gives humankind a slim chance at Tic Tac Toe survival.

    Chapter 14, Action!, takes you triumphantly back to Ticker Taker for the coup de grace—a bouncing camera rig built with Unity's built-in animation system that flies through a model of a hospital interior. By using the two-camera composite from The Break-Up, you'll create the illusion that the player is actually running through the hospital bouncing a heart on a tin tray. The chapter ends with a refresher on bundling your project and deploying it to the Web so that your millions of adoring fans (including your grandma) can finally experience your masterpiece.

    Appendix is an essentially vestigial component of the colon, which can be surgically removed if it gives you any trouble.

    What you need for this book

    You'll need to be in possession of a sturdy hat, a desk chair equipped with a seatbelt, and an array of delicious snack foods that won't get these pages all cheesy (if you're reading the e-book version, you're all set). Early chapters walk you through downloading and installing Unity 3D (http://unity3d.com/unity/download/). A list of resources and links to additional software can be found in the Appendix.

    Who this book is for

    If you've ever wanted to develop games, but have never felt smart enough to deal with complex programming, this book is for you. It's also a great kick start for developers coming from other tools like Flash, Unreal Engine, and Game Maker Pro.

    Conventions

    In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

    Code words in text are shown as follows: The audio.PlayOneShot command is perfect for collision sound effects.

    A block of code is set as follows:

    for(var i:int=0; i

    {

      var aRobotParts:List. = new List.();

     

      aRobotParts.Add(Head);

      aRobotParts.Add(Arm);

      aRobotParts.Add(Leg);

    }

    When we wish to draw indicate that a line of code needs to be added or edited, the relevant lines or items are set in bold:

    function Awake() {   startTime = Time.time + 5.0; }

    New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: When you click on the Apply button, Unity creates its set of raster images based on the font that you're importing.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

    To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title through the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the color images of this book

    We also provide you a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/5268OT_ColoredImages.pdf

    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.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. Each project in the book is intended to be built from the ground up, beginning with an new project file. The downloadable .unitypackage files for this book contain the assets (sounds, images, and models) you need to build the projects. You may also download completed, working versions of each project for your reference, though these are not intended to be your first stop – they're more like the answer sheet at the back of a text book.

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website, or added to any list of existing errata, under the Errata section of that

    Enjoying the preview?
    Page 1 of 1