ai game engine programming part 1下载

weixin_39821051 2019-05-11 10:00:16
ai game engine programming part 1
相关下载链接://download.csdn.net/download/falala4519/2172384?utm_source=bbsseo
...全文
39 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
Tricks of the Windows video Game Programming

PART I Windows Programming Foundations 7
1 Journey into the Abyss 9
A Little History........................................................................................9
Designing Games ..................................................................................13
Types of Games ....................................................................................13
Brainstorming........................................................................................14
The Design Document and Storyboards................................................15
Making the Game Fun ..........................................................................16
The Components of a Game..................................................................16
Section 1: Initialization....................................................................17
Section 2: Enter Game Loop............................................................17
Section 3: Retrieve Player Input ......................................................17
Section 4: Perform AI and Game Logic ..........................................17
Section 5: Render Next Frame ........................................................18
Section 6: Synchronize Display ......................................................18
Section 7: Loop................................................................................18
Section 8: Shutdown ........................................................................18
General Game Programming Guidelines ..............................................21
Using Tools............................................................................................26
C/C++ Compilers ............................................................................26
2D Art Software................................................................................26
Sound Processing Software..............................................................26
3D Modelers ....................................................................................26
Music and MIDI Sequencing Programs ..........................................27
Setting Up to Get Down—Using the Compiler ....................................27
An Example: FreakOut..........................................................................29
Summary................................................................................................46
2 The Windows Programming Model 47
The Genesis of Windows ......................................................................48
Early Windows Versions ..................................................................48
Windows 3.x ....................................................................................48
Windows 95......................................................................................49
Windows 98......................................................................................50
Windows NT ....................................................................................50
Basic Windows Architecture:Win9X/NT........................................50
Multitasking and Multithreading ..........................................................51
Getting Info on the Threads ............................................................52
The Event Model..............................................................................53

0072313618 FM 10/26/99 9:32 AM Page vi
vi
TRICKS OF THE WINDOWS GAME PROGRAMMING GURUS
Programming the Microsoft Way: Hungarian Notation........................55
Variable Naming ..............................................................................56
Function Naming..............................................................................56
Type and Constant Naming..............................................................57
Class Naming....................................................................................57
Parameter Naming............................................................................58
The World’s Simplest Windows Program..............................................58
It All Begins with
WinMain() ..........................................................59
Dissecting the Program....................................................................60
Choosing a Message Box ................................................................63
Real-World Windows Applications (Without Puck)..............................66
The Windows Class ..............................................................................66
Registering the Windows Class ............................................................74
Creating the Window ............................................................................75
The Event Handler ................................................................................77
The Main Event Loop............................................................................84
Making a Real-Time Event Loop..........................................................89
Opening More Windows........................................................................90
Summary................................................................................................93
3 Advanced Windows Programming 95
Using Resources....................................................................................96
Putting Your Resources Together ....................................................98
Using Icon Resources ......................................................................99
Using Cursor Resources ................................................................102
Creating String Table Resources....................................................106
Using Sound
.WAV Resources ........................................................108
Last, But Not Least—Using the Compiler to Create
.RC Files ....114
Working with Menus ..........................................................................116
Creating a Menu ............................................................................116
Loading a Menu..............................................................................119
Responding to Menu Event Messages ..........................................122
Introduction to GDI ............................................................................128
The
WM_PAINT Message Once Again ..............................................128
Video Display Basics and Color....................................................133
RGB and Palletized Modes............................................................135
Basic Text Printing ........................................................................137
Handling Important Events..................................................................143
Window Manipulation....................................................................143
Banging on the Keyboard ..............................................................150
Squeezing the Mouse......................................................................158
Sending Messages Yourself ................................................................161
Summary..............................................................................................163

0072313618 FM 10/26/99 9:32 AM Page vii
vii
CONTENTS
4 Windows GDI, Controls, and Last-Minute Gift Ideas 165
Advanced GDI Graphics......................................................................166
Under the Hood with the Graphics Device Context......................166
Color, Pens, and Brushes................................................................167
Working with Pens ........................................................................168
Painting with Brushes ....................................................................172
Points, Lines, Polygons, and Circles ..................................................173
Straight to the Point........................................................................173
Getting a Line on Things................................................................175
Getting Rectangular........................................................................177
Round and Round She Goes—Circles ..........................................180
Polygon, Polygon,Wherefore Art Thou, Polygon? ......................181
More on Text and Fonts ......................................................................182
Timing Is Everything ..........................................................................184
The
WM_TIMER Message ..................................................................184
Low-Level Timing..........................................................................187
Playing with Controls..........................................................................190
Buttons............................................................................................191
Sending Messages to Child Controls ............................................195
Getting Information ............................................................................197
The T3D Game Console......................................................................205
Summary..............................................................................................210
PART II DirectX and 2D Fundamentals 211
5 DirectX Fundamentals and the Dreaded COM 213
DirectX Primer ....................................................................................214
The HEL and HAL ........................................................................216
The DirectX Foundation Classes in Depth ....................................216
COM: Is It the Work of Microsoft… or Demons?..............................218
What Exactly Is a COM Object?....................................................219
More on Interface IDs and GUIDs ................................................223
Building a Quasi-COM Object ......................................................224
A Quick Recap of COM ................................................................226
A Working COM Program ............................................................226
Working with DirectX COM Objects..................................................231
COM and Function Pointers ..........................................................232
Creating and Using DirectX Interfaces..........................................236
Querying for Interfaces..................................................................237
The Future of COM ............................................................................238
Summary..............................................................................................239

0072313618 FM 10/26/99 9:32 AM Page viii
viii
TRICKS OF THE WINDOWS GAME PROGRAMMING GURUS
6 First Contact: DirectDraw 241
The Interfaces of DirectDraw..............................................................242
Interface Characteristics ................................................................242
Using the Interfaces Together ........................................................244
Creating a DirectDraw Object ............................................................245
Error Handling with DirectDraw....................................................246
Getting an Interface Lift ................................................................247
Cooperating with Windows ................................................................250
Getting into the Mode of Things ........................................................255
The Subtleties of Color........................................................................259
Building a Display Surface..................................................................263
Creating a Primary Surface............................................................264
Attaching the Palette......................................................................272
Plotting Pixels ................................................................................272
Cleaning Up....................................................................................284
Summary..............................................................................................285
7 Advanced DirectDraw and Bitmapped Graphics 287
Working with High-Color Modes........................................................288
16-Bit High-Color Mode................................................................289
Getting the Pixel Format................................................................290
24/32-Bit High-Color Mode ..........................................................299
Double Buffering ................................................................................301
Surface Dynamics................................................................................307
Page Flipping ......................................................................................311
Using the Blitter ..................................................................................317
Using the Blitter for Memory Filling ............................................320
Copying Bitmaps from Surface to Surface....................................328
Clipper Fundamentals..........................................................................332
Clipping Pixels to a Viewport ........................................................332
Clipping Bitmaps the Hard Way....................................................334
Making a DirectDraw Clip with
IDirectDrawClipper..................339
Working with Bitmaps ........................................................................345
Loading
.BMP files..........................................................................345
Working with Bitmaps....................................................................352
Loading an 8-Bit Bitmap................................................................353
Loading a 16-Bit Bitmap................................................................354
Loading a 24-Bit Bitmap................................................................355
Last Word on Bitmaps....................................................................356
Offscreen Surfaces ..............................................................................356
Creating Offscreen Surfaces ..........................................................356
Blitting Offscreen Surfaces............................................................358
Setting Up the Blitter......................................................................359
Color Keys......................................................................................360
Source Color Keying......................................................................361

0072313618 FM 10/26/99 9:32 AM Page ix
ix
CONTENTS
Destination Color Keying ..............................................................364
Using the Blitter (Finally!) ............................................................365
Bitmap Rotation and Scaling ..............................................................366
Discrete Sampling Theory ..................................................................368
Color Effects........................................................................................373
Color Animation in 256-Color Modes ..........................................373
Color Rotation in 256-Color Modes..............................................379
Tricks with RGB Modes ................................................................381
Manual Color Transforms and Lookup Tables....................................381
The New DirectX Color and Gamma Controls Interface....................382
Mixing GDI and DirectX ....................................................................383
Getting the Lowdown on DirectDraw ................................................386
The Main DirectDraw Object ........................................................386
Surfing on Surfaces........................................................................388
Playing with Palettes......................................................................389
Using DirectDraw in Windowed Modes..............................................390
Drawing Pixels in a Window..........................................................392
Finding the Real Client Area (51)..................................................395
Clipping a DirectX Window ..........................................................397
Working with 8-Bit Windowed Modes..........................................398
Summary..............................................................................................400
8 Vector Rasterization and 2D Transformations 401
Drawing Lines......................................................................................402
Bresenham’s Algorithm..................................................................403
Speeding Up the Algorithm............................................................409
Basic 2D Clipping................................................................................411
Computing the Intersection of Two Lines Using the Point
Slope Form ..................................................................................413
Computing the Intersection of Two Lines Using
the General Form ........................................................................416
Computing the Intersection of Two Lines Using
the Matrix Form ..........................................................................416
Clipping the Line............................................................................419
The Cohen-Sutherland Algorithm..................................................420
Wireframe Polygons............................................................................427
Polygon Data Structures ................................................................428
Drawing and Clipping Polygons....................................................430
Transformations in the 2D Plane ........................................................432
Translation......................................................................................433
Rotation..........................................................................................435
Scaling............................................................................................445
Introduction to Matrices......................................................................446
The Identity Matrix........................................................................448
Matrix Addition..............................................................................449

0072313618 FM 10/26/99 9:32 AM Page x
x
TRICKS OF THE WINDOWS GAME PROGRAMMING GURUS
Matrix Multiplication ....................................................................449
Transformations Using Matrices....................................................452
Translation ..........................................................................................454
Scaling..................................................................................................455
Rotation................................................................................................455
Solid Filled Polygons ..........................................................................458
Types of Triangles and Quadrilaterals............................................459
Drawing Triangles and Quadrilaterals............................................461
Triangular Deconstruction Details ................................................464
The General Case of Rasterizing a Quadrilateral..........................472
Triangulating Quads ......................................................................473
Collision Detection with Polygons......................................................478
Proximity AKA Bounding Sphere/Circle ......................................478
Bounding Box ................................................................................481
Point Containment..........................................................................484
More on Timing and Synchronization ................................................486
Scrolling and Panning..........................................................................488
Page Scrolling Engines ..................................................................488
Homogeneous Tile Engines............................................................489
Sparse Bitmap Tile Engines ..........................................................494
Fake 3D Isometric Engines..................................................................496
Method 1: Cell-Based, Totally 2D ................................................496
Method 2: Full-Screen-Based, with 2D or 3D
Collision Networks......................................................................498
Method 3: Using Full 3D Math, with a Fixed Camera View ........500
The T3DLIB1 Library ........................................................................500
The Engine Architecture ................................................................500
Basic Definitions............................................................................501
Working Macros ............................................................................502
Data Types and Structures..............................................................503
Global Domination ........................................................................506
The DirectDraw Interface ..............................................................507
2D Polygon Functions....................................................................511
2D Graphic Primitives....................................................................513
Math and Error Functions..............................................................517
Bitmap Functions............................................................................519
Palette Functions............................................................................522
Utility Functions ............................................................................525
The BOB (Blitter Object) Engine........................................................527
Summary..............................................................................................535
9 Uplinking with DirectInput and Force Feedback 537
The Input Loop Revisited....................................................................538
DirectInput Overture............................................................................539
The Components of DirectInput ....................................................541
The General Steps for Setting Up DirectInput ..............................542

0072313618 FM 10/26/99 9:32 AM Page xi
xi
CONTENTS
Data Acquisition Modes ................................................................544
Creating the Main DirectInput Object............................................544
The 101-Key Control Pad ..............................................................546
Problem During Reading: Reacquisition........................................554
Trapping the Mouse........................................................................556
Working the Joystick......................................................................561
Massaging Your Input ....................................................................576
Going Deeper with Force Feedback....................................................579
The Physics of Force Feedback......................................................580
Setting Up Force Feedback............................................................580
A Force Feedback Demo................................................................581
Writing a Generalized Input System:
T3DLIB2.CPP ............................582
The T3D Library at a Glance ........................................................588
Summary..............................................................................................588
10 Sounding Off with DirectSound and DirectMusic 589
Sound Programming on the PC ..........................................................589
And Then There Was Sound…............................................................590
Digital versus MIDI—Sounds Great, Less Filling..............................594
Digital Sound—Let the Bits Begin................................................594
Synthesized Sound and MIDI........................................................596
It’s MIDI Time!..............................................................................597
Sound Hardware..................................................................................598
Wave Table Synthesis ....................................................................598
Wave Guide Synthesis....................................................................598
Digital Recording: Tools and Techniques............................................599
Recording Sounds ..........................................................................600
Processing Your Sounds ................................................................600
DirectSound on the Mic ......................................................................601
Starting Up DirectSound......................................................................602
Understanding the Cooperation Level............................................604
Setting the Cooperation Level........................................................605
Primary and Secondary Sound Buffers ..............................................606
Working with Secondary Buffers ..................................................606
Creating Secondary Sound Buffers................................................607
Writing Data to Secondary Buffers................................................610
Rendering Sounds................................................................................612
Playing a Sound..............................................................................612
Stopping a Sound............................................................................612
Controlling the Volume..................................................................612
Freaking with the Frequency..........................................................613
Panning in 3D ................................................................................614
Making DirectSound Talk Back..........................................................614
Reading Sounds from Disk..................................................................616
The
.WAV Format ............................................................................616
Reading
.WAV Files ........................................................................617

0072313618 FM 10/26/99 9:32 AM Page xii
xii
TRICKS OF THE WINDOWS GAME PROGRAMMING GURUS
DirectMusic: The Great Experiment ..................................................622
DirectMusic Architecture ....................................................................622
Starting Up DirectMusic......................................................................624
Initializing COM............................................................................624
Creating the Performance ..............................................................625
Adding a Port to the Performance..................................................626
Loading a MIDI Segment....................................................................626
Creating the Loader........................................................................627
Loading the MIDI File ..................................................................627
Manipulating MIDI Segments ............................................................630
Playing a MIDI Segment................................................................630
Stopping a MIDI Segment..............................................................631
Checking the Status of a MIDI Segment ......................................631
Releasing a MIDI Segment............................................................631
Shutting Down DirectMusic ..........................................................631
A Little DirectMusic Example ......................................................632
The
T3DLIB3 Sound and Music Library ..............................................632
The Header ....................................................................................633
The Types ......................................................................................633
Global Domination ........................................................................634
The DirectSound API Wrapper......................................................635
The DirectMusic API Rapper—Get It?..........................................640
Summary..............................................................................................643
PART III Hard Core Game Programming 645
11 Algorithms, Data Structures, Memory Management,
and Multithreading 647
Data Structures ....................................................................................648
Static Structures and Arrays ..........................................................648
Linked Lists....................................................................................649
Algorithmic Analysis ..........................................................................657
Recursion ............................................................................................659
Trees ....................................................................................................662
Building BSTs................................................................................666
Searching BSTs..............................................................................668
Optimization Theory............................................................................671
Using Your Head ............................................................................671
Mathematical Tricks ......................................................................672
Fixed-Point Math............................................................................673
Unrolling the Loop ........................................................................677
Look-Up Tables..............................................................................678
Assembly Language ......................................................................679
Making Demos ....................................................................................680
Prerecorded Demos........................................................................680
AI-Controlled Demos ....................................................................682

0072313618 FM 10/26/99 9:32 AM Page xiii
xiii
CONTENTS
Strategies for Saving the Game ..........................................................682
Implementing Multiple Players ..........................................................683
Taking Turns ..................................................................................683
Split-Screen Setups ........................................................................684
Multithreaded Programming Techniques ............................................685
Multithreaded Programming Terminology ....................................686
Why Use Threads in a Game?........................................................687
Conjuring a Thread from the Plasma Pool ....................................689
Sending Messages from Thread to Thread ....................................697
Waiting for the Right Moment ......................................................702
Multithreading and DirectX ..........................................................709
Advanced Multithreading ..............................................................711
Summary..............................................................................................711
12 Making Silicon Think with Artificial Intelligence 713
Artificial Intelligence Primer ..............................................................714
Deterministic AI Algorithms................................................................715
Random Motion..............................................................................716
Tracking Algorithms ......................................................................717
Anti-Tracking: Evasion Algorithms ..............................................722
Patterns and Basic Control Scripting ..................................................722
Basic Patterns ................................................................................723
Patterns with Conditional Logic Processing..................................727
Modeling Behavioral State Systems....................................................729
Elementary State Machines............................................................730
Adding More Robust Behaviors with Personality..........................734
Modeling Memory and Learning with Software ................................736
Planning and Decision Trees ..............................................................740
Coding Plans ..................................................................................742
Implementing a Real Planner ........................................................745
Pathfinding ..........................................................................................747
Trial and Error................................................................................748
Contour Tracing..............................................................................749
Collision Avoidance Tracks............................................................749
Waypoint Pathfinding ....................................................................750
A Racing Example..........................................................................753
Robust Pathfinding ........................................................................754
Advanced AI Scripting ........................................................................759
Designing the Scripting Language ................................................759
Using the C/C++ Compiler............................................................762
Artificial Neural Networks..................................................................767
Genetic Algorithms..............................................................................770
Fuzzy Logic ........................................................................................772
Normal Set Theory ........................................................................773
Fuzzy Set Theory............................................................................774

0072313618 FM 10/26/99 9:32 AM Page xiv
xiv
TRICKS OF THE WINDOWS GAME PROGRAMMING GURUS
Fuzzy Linguistic Variables and Rules............................................776
Fuzzy Manifolds and Membership ................................................779
Fuzzy Associative Matrices............................................................783
Processing the FAM with the Fuzzified Inputs..............................787
Warm and Fuzzy ............................................................................794
Building Real AI for Games................................................................794
Summary..............................................................................................795
13 Playing God: Basic Physics Modeling 797
Fundamental Laws of Physics ............................................................798
Mass (m) ........................................................................................799
Time (t) ..........................................................................................799
Position (s)......................................................................................800
Velocity (v) ....................................................................................802
Acceleration (a)..............................................................................804
Force (F) ........................................................................................807
Forces in Higher Dimensions ........................................................808
Momentum (P)................................................................................809
The Physics of Linear Momentum: Conservation and Transfer ........810
Modeling Gravity Effects....................................................................813
Modeling a Gravity Well................................................................815
Modeling Projectile Trajectories....................................................818
The Evil Head of Friction....................................................................821
Basic Friction Concepts..................................................................821
Friction on an Inclined Plane (Advanced) ....................................823
Basic Ad Hoc Collision Response ......................................................828
Simple x,y Bounce Physics............................................................828
Computing the Collision Response with Planes of
Any Orientation ..........................................................................830
An Example of Vector Reflection..................................................834
Intersection of Line Segments........................................................835
Real 2D Object-to-Object Collision Response (Advanced)................841
Resolving the n-t Coordinate System..................................................846
Simple Kinematics ..............................................................................853
Solving the Forward Kinematic Problem ......................................854
Solving the Inverse Kinematic Problem ........................................858
Particle Systems ..................................................................................859
What Every Particle Needs ............................................................859
Designing a Particle Engine ..........................................................860
The Particle Engine Software ........................................................861
Generating the Initial Conditions ..................................................866
Putting the Particle System Together ............................................869
Playing God: Constructing Physics Models for Games......................870
Data Structures for Physics Modeling............................................870
Frame-Based Versus Time-Based Modeling..................................871
Summary..............................................................................................873

0072313618 FM 10/26/99 9:32 AM Page xv
xv
CONTENTS
14 Putting It All Together: You Got Game! 875
The Initial Design of Outpost..............................................................876
The Story........................................................................................876
Designing the Gameplay................................................................877
The Tools Used to Write the Game ....................................................877
The Game Universe: Scrolling in Space..............................................878
The Player’s Ship: “The Wraith” ........................................................880
The Asteroid Field ..............................................................................882
The Enemies........................................................................................884
The Outposts ..................................................................................885
The Predator Mines........................................................................886
The Gunships..................................................................................888
The Power-Ups....................................................................................891
The HUDS ..........................................................................................892
The Particle System ............................................................................896
Playing the Game ................................................................................896
Compiling Outpost ..............................................................................897
Compilation Files ..........................................................................897
Runtime Files..................................................................................898
Epilogue ..............................................................................................898
P
ART IV Appendixes 901
A What’s on the CD 903
B Installing DirectX and Using the C/C++ Compiler 907
Using the C/C++ Compiler..................................................................908
C Math and Trigonometry Review 911
Trigonometry ......................................................................................911
Vectors..................................................................................................915
Vector Length ................................................................................916
Normalization ................................................................................917
Scalar Multiplication......................................................................917
Vector Addition ..............................................................................918
Vector Subtraction..........................................................................919
The Inner Product, or the “Dot” Product ......................................919
The Cross Product..........................................................................921
The Zero Vector..............................................................................923
Position Vectors..............................................................................923
Vectors as Linear Combinations ....................................................924

0072313618 FM 10/26/99 9:32 AM Page xvi
xvi
TRICKS OF THE WINDOWS GAME PROGRAMMING GURUS
D C++ Primer 925
What Is C++? ......................................................................................925
The Minimum You Need to Know About C++ ..................................928
New Types, Keywords, and Conventions............................................929
Comments ......................................................................................929
Constants........................................................................................929
Referential Variables ......................................................................929
Creating Variables On-the-Fly........................................................930
Memory Management..........................................................................931
Stream I/O............................................................................................932
Classes..................................................................................................934
The New Struct in Town ................................................................934
Just a Simple Class ........................................................................935
Public Versus Private......................................................................936
Class Member Functions (A.K.A. Methods) ................................937
Constructors and Destructors ........................................................938
Writing a Constructor ....................................................................939
Writing a Destructor ......................................................................941
The Scope Resolution Operator ..........................................................943
Function and Operator Overloading....................................................945
Summary..............................................................................................947
E Game Programming Resources 949
Game Programming Sites....................................................................949
Download Points..................................................................................950
2D/3D Engines ....................................................................................950
Game Programming Books..................................................................951
Microsoft DirectX Multimedia Exposition..........................................951
Usenet Newsgroups ............................................................................951
Keeping Up with the Industry: Blues News........................................952
Game Development Magazines ..........................................................952
Game Web Site Developers ................................................................953
Xtreme Games LLC ............................................................................953
F ASCII Tables 955
Index 961
Acknowledgments xiii Introduction xv 1. Making Games the Modular Way 1 1.1 Important Programming Concepts.....................................2 1.1.1 Manager and Controller Scripts...............................2 1.1.2 Script Communication.......................................3 1.1.3 Using the Singleton Pattern in Unity...........................5 1.1.4 Inheritance.................................................6 1.1.5 Where to Now?.............................................8 2. Building the Core Game Framework 9 2.1 Controllers and Managers............................................11 2.1.1 Controllers................................................11 2.1.2 Managers.................................................11 2.2 Building the Core Framework Scripts..................................11 2.2.1 BaseGameController.cs.....................................12 2.2.1.1 Script Breakdown................................14 viii Contents 2.2.2 Scene Manager.............................................17 2.2.2.1 Script Breakdown................................17 2.2.3 ExtendedCustomMonoBehavior.cs...........................19 2.2.4 BaseUserManager.cs........................................20 2.2.4.1 Script Breakdown................................22 2.2.5 BasePlayerManager.cs.......................................22 2.2.5.1 Script Breakdown................................23 2.2.6 BaseInputController.cs......................................24 2.2.6.1 Script Breakdown................................26 3. Player Structure 29 3.1 Game-Specific Player Controller......................................31 3.2 Dealing with Input..................................................32 3.3 Player Manager.....................................................35 3.3.1 Script Breakdown..........................................36 3.4 User Data Manager (Dealing with Player Stats Such as Health, Lives, etc.)....37 3.4.1 Script Breakdown..........................................39 4. Recipes: Common Components 41 4.1 Introduction.......................................................41 4.2 The Timer Class....................................................43 4.2.1 Script Breakdown..........................................45 4.3 Spawn Scripts......................................................48 4.3.1 A Simple Spawn Controller..................................49 4.3.1.1 Script Breakdown................................52 4.3.2 Trigger Spawner...........................................56 4.3.3 Path Spawner..............................................57 4.3.3.1 Script Breakdown................................61 4.4 Set Gravity.........................................................66 4.5 Pretend Friction—Friction Simulation to Prevent Slipping Around........66 4.5.1 Script Breakdown..........................................68 4.6 Cameras. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68 4.6.1 Third-Person Camera.......................................69 4.6.1.1 Script Breakdown................................71 4.6.2 Top-Down Camera.........................................74 4.6.2.1 Script Breakdown................................74 4.7 Input Scripts.......................................................75 4.7.1 Mouse Input...............................................75 4.7.1.1 Script Breakdown................................76 4.7.2 Single Axis Keyboard Input.................................78 4.8 Automatic Self-Destruction Script.....................................79 4.8.1 Script Breakdown..........................................79 4.9 Automatic Object Spinner............................................79 4.9.1 Script Breakdown..........................................80 ix Contents 4.10 Scene Manager.....................................................81 4.10.1 Script Breakdown..........................................82 5. Building Player Movement Controllers 85 5.1 Shoot ’Em Up Spaceship.............................................85 5.2 Humanoid Character................................................91 5.2.1 Script Breakdown..........................................96 5.3 Wheeled Vehicle...................................................106 5.3.1 Script Breakdown.........................................109 5.3.2 Wheel Alignment.........................................114 5.3.3 Script Breakdown.........................................116 6. Weapon Systems 121 6.1 Building the Scripts................................................122 6.1.1 BaseWeaponController.cs..................................122 6.1.1.1 Script Breakdown...............................127 6.1.2 BaseWeaponScript.cs......................................134 6.1.2.1 Script Breakdown...............................138 7. Recipe: Waypoints Manager 143 7.1 Waypoint System..................................................143 8. Recipe: Sound Manager 157 8.1 The Sound Controller...............................................158 8.1.1 Script Breakdown.........................................160 8.2 The Music Player...................................................163 8.2.1 Script Breakdown.........................................165 8.3 Adding Sound to the Weapons.......................................167 9. AI Manager 169 9.1 The AI State Control Script..........................................171 9.2 The Base AI Control Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 9.2.1 Script Breakdown.........................................185 9.3 Adding Weapon Control to the AI Controller..........................206 9.3.1 Script Breakdown.........................................210 10. Menus and User Interface 215 10.1 The Main Menu....................................................215 10.1.1 Script Breakdown.........................................223 10.2 In-Game User Interface.............................................231 x Contents 11. Dish: Lazer Blast Survival 233 11.1 Main Menu Scene..................................................235 11.2 Main Game Scene..................................................236 11.3 Prefabs...........................................................237 11.4 Ingredients........................................................238 11.5 Game Controller...................................................239 11.5.1 Script Breakdown.........................................243 11.6 Player Controller...................................................250 11.6.1 Script Breakdown.........................................253 11.7 Enemies..........................................................259 11.7.1 Script Breakdown.........................................260 11.8 Wave Spawning and Control........................................261 11.8.1 Script Breakdown.........................................263 11.9 Wave Properties...................................................265 11.10 Weapons and Projectiles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..266 11.11 User Interface.....................................................266 11.11.1 Script Breakdown.........................................267 12. Dish: Metal Vehicle Doom 271 12.1 Main Menu Scene..................................................272 12.2 Main Game Scene..................................................272 12.2.1 Prefabs...................................................275 12.3 Ingredients........................................................275 12.3.1 Game Controller..........................................276 12.3.1.1 Script Breakdown...............................282 12.3.2 Race Controller...........................................291 12.3.2.1 Script Breakdown...............................297 12.3.3 Global Race Manager......................................306 12.3.3.1 Script Breakdown...............................311 12.3.4 Vehicle/Custom Player Control.............................318 12.3.4.1 Script Breakdown...............................327 12.3.5 User Interface.............................................344 13. Dish: Making the Game Tank Battle 345 13.1 Main Game Scene..................................................347 13.2 Prefabs...........................................................349 13.3 Ingredients........................................................349 13.4 Game Controller...................................................350 13.4.1 Script Breakdown.........................................356 13.5 Battle Controller...................................................361 13.5.1 Script Breakdown.........................................363 13.6 Global Battle Manager..............................................364 13.6.1 Script Breakdown.........................................368 13.7 Players............................................................373 13.7.1 Script Breakdown.........................................382 xi Contents 13.8 AI Chasing with SetAIChaseTargetBasedOnTag.cs.....................383 13.8.1 Script Breakdown.........................................385 14. Dish: Making the Game Interstellar Paranoids 389 14.1 Main Menu.......................................................392 14.2 Game Scenes......................................................392 14.3 Prefabs...........................................................393 14.3.1 Ingredients...............................................394 14.3.2 Game Controller..........................................395 14.3.2.1 Script Breakdown...............................401 14.3.3 Player Spaceship..........................................411 14.3.3.1 Script Breakdown...............................415 14.3.4 Enemies..................................................423 14.3.4.1 Script Breakdown...............................424 14.3.5 Waypoint Follower........................................426 14.3.5.1 Script Breakdown...............................427 Final Note 429 xiii I would like to thank my wife for all the encouragement, support, and nice cups of tea. I would also like to thank my mum and dad, my brother Steve, and everyone else who knows me. Sophie cat, be nice to the boys. Sincere thanks go to the many people who positively influence my life directly or indirectly: Michelle Ashton, Brian Robbins, George Bray, Nadeem Rasool, Christian Boutin, James and Anna, Rich and Sharon, Liz and Peter, Rob Fearon (the curator of all things shiny), everyone on Twitter who RTs my babble (you know who you are, guys!), Matthew Smith (the creator of Manic Miner), David Braben, Tōru Iwatani, and anyone who made Atari games in the 1980s. I would like to thank everyone at AK Peters/CRC Press for the help and support and for publishing my work. Finally, a massive thank you goes out to you for buying this book and for wanting to do something as cool as to make games. I sincerely hope this book helps your gamemaking adventures—feel free to tell me about them on Twitter @psychicparrot or drop by my website at http://www.psychicparrot.com. Acknowledgments xv As I was starting out as a game developer, as a self-taught programmer my skills took a while to reach a level where I could achieve what I wanted. Sometimes I wanted to do things that I just didn’t have yet the technical skills to achieve. Now and again, software packages came along that could either help me in my quest to make games or even make full games for me; complete game systems such as the Shoot ’Em-Up Construction Kit (aka SEUCK) from Sensible Software, Gary Kitchen’s GameMaker, or The Quill Adventure System could bring to life the kinds of games that went way beyond anything that my limited programming skills could ever dream of building. The downside to using game creation software was that it was tailored to create games within their chosen specific genre. If I wanted to do something outside of the limitations of the software, the source code was inaccessible and there was no way to extend or modify it. When that happened, I longed for a modular code-based system that I could plug together to create different types of games but modify parts of it without having to spend a lot of time learning how the entire system internals work—building block game development that I could actually script and modify if I needed to. After completing my first book, Game Development for iOS with Unity3D, I wanted to follow up by applying a modular style of game building to Unity3D that would provide readers with a highly flexible framework to create just about any kind of game by “plugging in” the different script components. My intention was to make a more technical second book, based on C# programming, that would offer extensibility in any direction a developer might require. In essence, what you are holding in your hands right now is a cookbook Introduction xvi Introduction for game development that has a highly flexible core framework for just about any type of game. A lot of the work I put in at the start of writing this book was in designing a framework that not only made sense in the context of Unity but also could easily cope with the demands of different genres. Prerequisites You can get up and running with the required software for the grand total of zero dollars. Everything you need can be downloaded free of charge with no catches. You may want to consider an upgrade to Unity Pro at some point in the future, to take advantage of some of its advanced features, but to get started all you need to do is grab the free version from the Unity website. Unity Free or Unity Pro (available from the Unity store at http://www.unity3d.com) Unity Free is completely free for anyone or any company making less than $100,000 per year—it may be downloaded for no charge at all, and you don’t even need a credit card. It’s a really sweet deal! We are talking about a fully functional game engine, ready to make 3D or 2D games that may be sold commercially or otherwise. There are no royalties to pay, either. Unity Pro adds a whole host of professional functionality to the engine, such as render culling and profiling. If you are a company with more than $100,000 per year of turnover, you will need a Pro license, but if you find that Unity Free doesn’t pack quite enough power, you may also want to consider going Pro. You can arrange a free trial of the Pro version right from the Unity website to try before you buy. If the trial licence runs out before you feel you know enough to make a purchase, contact Unity about extending it and they are usually very friendly and helpful about it (just don’t try using a trial license for 6 months at a time, as they may just figure it out!). C# programming knowledge Again, to reiterate this very important point, this is nota book about learning how to program. You will need to know some C#, and there are a number of other books out there for that purpose, even if I have tried to make the examples as simple as possible! This book is about making games, not about learning to program. What This Book Doesn’t Cover This is not a book about programming and it is not a book about the right or wrong way to do things. We assume that the reader has some experience with the C# programming language. I am a self-taught programmer, and I understand that there may well be better ways to do things. xvii Introduction This is a book about concepts, and it is inevitable that there will be better methods for achieving some of the same goals. The techniques and concepts offered in this book are meant to provide solid foundation, not to be the final word on any subject. It is the author’s intention that, as you gain your own experiences in game development, you make your own rules and draw your own conclusions. Additional material is available from the CRC Press Web site: http://www.crcpress. com/product/isbn/9781466581401. 1 1 Making Games the Modular Way When I first started making games, I would approach development on a project-to-project basis, recoding and rebuilding everything from scratch each time. As I became a professional developer, landing a job at a game development studio making browser-based games, I was lucky enough to work with a guy who was innovating the scene. He was a master at turning out great games (both visually and gameplay-wise) very quickly. One secret to his success lay in the development of a reusable framework that could easily be refactored to use on all of his projects. His framework was set up to deal with server communication, input handling, browser communication, and UI among other things, saving an incredible amount of time in putting together all of the essentials. By reusing the framework, it allowed more time for him and his team to concentrate on great gameplay and graphics optimization, resulting in games that, at the time, blew the competition away. Of course, the structure was tailored to how he worked (he did build it, after all), and it took me a while to get to grips with his style of development; but once I did, it really opened my eyes. From then on, I used the framework for every project and even taught other programmers how to go about using it. Development time was substantially reduced, which left more time to concentrate on making better games. This book is based on a similar concept of a game-centric framework for use with many different types of games, rather than a set of different games in different styles. The overall goal of this book is to provide script-based components that you can use within that framework to make a head start with your own projects in a way that reduces recoding, repurposing, or adaptation time. 2 1. Making Games the Modular Way In terms of this book as a cookbook, think of the framework as a base soup and the scripting components as ingredients. We can mix and match script components from different games that use the same framework to make new games, and we can share several of the same core scripts in many different games. The framework takes care of the essentials, and we add a little “glue” code to pull everything together the way we want it all to work. This framework is, of course, optional, but you should spend some time familiarizing yourself with it to help understand the book. If you intend to use the components in this book for your own games, the framework may serve either as a base to build your games on or simply as a tutorial test bed for you to rip apart and see how things work. Perhaps you can develop a better framework or maybe you already have a solid framework in place. If you do, find a way to develop a cleaner, more efficient framework or even a framework that isn’t quite so efficient but works better with your own code, and do it. In this chapter, we start by examining some of the major programming concepts used in this book and look at how they affect the design decisions of the framework. 1.1 Important Programming Concepts I had been programming in C# for a fairly long time before I actually sat down and figured out some of the concepts covered in this chapter. It was not because of any particular problem or difficulty with the concepts themselves but more because I had solved the problems in a different way that meant I had no real requirement to learn anything new. For most programmers, these concepts will be second nature and perhaps something taught in school, but I did not know how important they could be. I had heard about things like inheritance, and it was something I put in the to-do list, buried somewhere under “finish the project.” Once I took the time to figure them out, they saved me a lot of time and led to much cleaner code than I would have previously pulled together. If there’s something you are unsure about, give this chapter a read-through and see whether you can work through the ideas. Hopefully, they may save some of you some time in the long run. 1.1.1 Manager and Controller Scripts I am a strong believer in manager and controller scripts. I like to try and split things out into separate areas; for example, in the Metal Vehicle Doomgame, I have race controller scripts and a global race controller script. The race controller scripts are attached to the players and track their positions on the track, waypoints, and other relevant player-specific race information. The global race controller script talks to all the race controller scripts attached to the players to determine who is winning and when the race starts or finishes. By keeping this logic separate from the other game scripts and contained in their own controller scripts, it makes it easier to migrate them from project to project. Essentially, I can take the race controller and global race controller scripts out of the game and apply them to another game, perhaps one that features a completely different type of gameplay— for example, alien characters running around a track instead of cars. As long as I apply the correct control scripts, the race logic is in place, and I can access it in the new game. In the framework that this book contains, there are individual manager and controller scripts dealing with user data, input, game functions, and user interface. We look at those in detail in Chapter 2, but as you read this chapter, you should keep in mind the idea of separated scripts dedicated to managing particular parts of the game structure. It was 3 1.1 Important Programming Concepts important to me to design scripts as standalone so that they may be used in more than one situation. For example, our weapon slot manager will not care what kind of weapon is in any of the slots. The weapon slot manager is merely an interface between the player and the weapon, taking a call to “fire” and responding to it by telling the weapon in the currently selected weapon slot to fire. What happens on the player end will not affect the slot manager just as anything that happens with the weapon itself will not affect the slot manager. It just doesn’t care as long as your code talks to it in the proper way and as long as your weapons receive commands in the proper way. It doesn’t even matter what type of object the slot manager is attached to. If you decide to attach the weapon slot manager to a car, a boat, a telegraph pole, etc., it doesn’t really matter just as long as when you want them to fire, you use the correct function in the slot manager to get it to tell a weapon to fire. Since our core game logic is controlled by manager and controller scripts, we need to be a little smart about how we piece everything together. Some manager scripts may benefit from being static and available globally (for all other scripts to access), whereas others may be better attached to other scripts. We deal with these on a case-by-case basis. To get things started, we will be looking at some of the ways that these manager scripts can communicate with each other. As a final note for the topic in this section, you may be wondering what the difference is between managers and controllers. There really isn’t all that much, and I have only chosen to differentiate for my own sanity. I see controllers as scripts that are larger global systems, such as game state control, and managers as smaller scripts applied to gameObjects, such as weapon slot management or physics control. The terms are applied loosely, so don’t worry if there appear to be inconsistencies in the application of the term in one case versus another. I’ll try my best to keep things logical, but that doesn’t mean it’ll always make sense to everyone else! 1.1.2 Script Communication An important part of our manager- and component-based structures is how our scripts are going to communicate with each other. It is inevitable that we will need to access our scripts from a multitude of other areas of the game, which means we should try to provide interfaces that make the most sense. There are several different ways of communicating between scripts and objects in Unity: 1. Direct referencing manager scripts via variables set in the editor by the Inspector window. The easiest way to have your scripts talk to each other is to have direct references to them in the form of public variables within a class. They are populated in the Unity editor with a direct link to another script. Here is an example of direct referencing: public void aScript otherScript; In the editor window, the Inspector shows the otherScript field. We drag and drop an object containing the script component that we want to talk to. Within the class, function calls are made directly on the variable, such as otherScript.DoSomething(); 4 1. Making Games the Modular Way 2. GameObject referencing using SendMessage. SendMessage is a great way to send a message to a gameObject and call a function in one of its attached scripts or components when we do not need any kind of return result. For example, SomeGameObject.SendMessage("DoSomething"); SendMessage may also take several parameters, such as setting whether or not the engine should throw an error when there is no receiver, that is, no function in any script attached to the gameObject with a name matching the one in the SendMessage call. (SendMessageOptions). You can also pass one parameter into the chosen function just as if you were passing it via a regular function call such as SomeGameObject.SendMessage("AddScore",2); SomeGameObject.SendMessage("AddScore", SendMessageOptions.RequireReceiver); SomeGameObject.SendMessage("AddScore", SendMessageOptions.DontRequireReceiver); 3. Static variables. The static variable type is useful in that it extends across the entire system; it will be accessible in every other script. This is a particularly useful behavior for a game control script, where several different scripts may want to communicate with it to do things such as add to the player’s score, lose a life, or perhaps change a level. An example declaration of a static variable might be private static GameController aController; Although static variables extend across the entire program, you can have private and public static variables. Things get a little tricky when you try to understand the differences between public and private static types—I was glad to have friends on Twitter that could explain it all to me, so let me pass on what I was told: Public static A public static variable exists everywhere in the system and may be accessed from other classes and other types of script. Imagine a situation where a player control script needs to tell the game controller script whenever a player picks up a banana. We could deal with it like this: 1. In our gamecontroller.cs game controller script, we set up a public static: public static GameController gateway; 2. When the game controller (gamecontroller.cs) runs its Start() function, it stores a reference to itself in a public static variable like this: gateway = this; 3. In any other class, we can now access the game controller by referring to its type followed by that static variable (GameController.gateway) such as GameController.gateway.GotBanana(); 5 1.1 Important Programming Concepts Private static A private static variable exists within the class it was declared and in any other instances of the same class. Other classes/types of script will not be able to access it. As a working example, try to imagine that a script named player.cs directly controls player objects in your game. They all need to tell a player manager script when something happens, so we declare the player manager as a static variable in our player.cs script like this: private static PlayerManager playerManager; The playerManager object only needs to be set up once, by a single instance of the player class, to be ready to use for all the other instances of the same class. All player.cs scripts will be able to access the same instance of the PlayerManager. 4. The singleton design pattern. In the previous part of this section, we looked at using a static variable to share a manager script across the entire game code. The biggest danger with this method is that it is possible to create multiple instances of the same script. If this happens, you may find that your player code is talking to the wrong instance of the game controller. A singletonis a commonly used design pattern that allows for only one instance of a particular class to be instantiated at a time. This pattern is ideal for our game scripts that may need to communicate (or be communicated with) across the entire game code. Note that we will be providing a static reference to the script, exactly as we did in the “Static Variables” method earlier in this section, but in implementing a singleton class, we will be adding some extra code to make sure that only one instance of our script is ever created. 1.1.3 Using the Singleton Pattern in Unity It is not too difficult to see how useful static variables can be in communication between different script objects. In the public static example cited earlier, the idea was that we had a game controller object that needed to be accessed from one or more other scripts in our game. The method shown here was demonstrated on the Unity public wiki*by a user named Emil Johansen (AngryAnt). It uses a private static variable in conjunction with a public static function. Other scripts access the public function to gain access to the private static instance of this script, which is returned via the public function so that only one instance of the object will ever exist in a scene regardless of how many components it is attached to and regardless of how many times it is instantiated. A simple singleton structure: public class MySingleton { private static MySingleton instance; public MySingleton () *http://wiki.unity3d.com/index.php/Singleton. 6 1. Making Games the Modular Way { if (instance != null) { Debug.LogError ("Cannot have two instances of singleton."); return; } instance = this; } public static MySingleton Instance { get { if (instance == null) { new MySingleton (); } return instance; } } } The singleton instance of our script may be accessed anywhere, by any script, simply with the following syntax: MySingleton.Instance.MySingletonMember; 1.1.4 Inheritance Inheritanceis a complex concept, which demands some explanation here because of its key role within the scripts provided in this book. Have a read through this section, but don’t worry if you don’t pick up inheritance right away. Once we get to the programming, it will most likely become clear. The bottom line is that inheritance is used in programming to describe a method of providing template scripts that may be overridden, or added to, by other scripts. As a metaphor, imagine a car. All cars have four wheels and an engine. The types of wheels may vary from car to car, as will the engine, so when we say “this is a car” and try to describe how our car behaves, we may also describe the engine and wheels. These relationships may be shown in a hierarchical order: Car -Wheels -Engine Now try to picture this as a C# script: Car class Wheels function Engine function 7 1.1 Important Programming Concepts

13,656

社区成员

发帖
与我相关
我的任务
社区描述
CSDN 下载资源悬赏专区
其他 技术论坛(原bbs)
社区管理员
  • 下载资源悬赏专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧