Tải bản đầy đủ (.pdf) (290 trang)

Ebook 3D game programming for kids (Second edition): Part 1

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.82 MB, 290 trang )


3DGameProgrammingfor
Kids,SecondEdition
CreateInteractiveWorldswithJavaScript
byChrisStrom
Version:P1.0(July2018)


Copyright©2018ThePragmaticProgrammers,LLC.Thisbookislicensedtotheindividualwho
purchasedit.Wedon'tcopy-protectitbecausethatwouldlimityourabilitytouseitforyourownpurposes.
Pleasedon'tbreakthistrust—youcanusethisacrossallofyourdevicesbutpleasedonotsharethiscopy
withothermembersofyourteam,withfriends,orviafilesharingservices.Thanks.
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedas
trademarks.Wherethosedesignationsappearinthisbook,andThePragmaticProgrammers,LLCwas
awareofatrademarkclaim,thedesignationshavebeenprintedininitialcapitallettersorinallcapitals.The
PragmaticStarterKit,ThePragmaticProgrammer,PragmaticProgramming,PragmaticBookshelfandthe
linkinggdevicearetrademarksofThePragmaticProgrammers,LLC.
Everyprecautionwastakeninthepreparationofthisbook.However,thepublisherassumesno
responsibilityforerrorsoromissions,orfordamagesthatmayresultfromtheuseofinformation(including
programlistings)containedherein.

AboutthePragmaticBookshelf
ThePragmaticBookshelfisanagilepublishingcompany.We’reherebecausewewanttoimprovethelives
ofdevelopers.Wedothisbycreatingtimely,practicaltitles,writtenbyprogrammersforprogrammers.
OurPragmaticcourses,workshops,andotherproductscanhelpyouandyourteamcreatebettersoftware
andhavemorefun.Formoreinformation,aswellasthelatestPragmatictitles,pleasevisitusat
.
OurebooksdonotcontainanyDigitalRestrictionsManagement,andhavealwaysbeenDRM-free.We
pioneeredthebetabookconcept,whereyoucanpurchaseandreadabookwhileit’sstillbeingwritten,and
providefeedbacktotheauthortohelpmakeabetterbookforeveryone.Freeresourcesforallpurchasers
includesourcecodedownloads(ifapplicable),errataanddiscussionforums,allavailableonthebook's


homepageatpragprog.com.We’reheretomakeyourlifeeasier.
NewBookAnnouncements
Wanttokeepuponourlatesttitlesandannouncements,andoccasionalspecialoffers?Justcreatean
accountonpragprog.com(anemailaddressandapasswordisallittakes)andselectthecheckboxto
receivenewsletters.Youcanalsofollowusontwitteras@pragprog.
AboutEbookFormats
Ifyoubuydirectlyfrompragprog.com,yougetebooksinallavailableformatsforoneprice.Youcansynch
yourebooksamongstallyourdevices(includingiPhone/iPad,Android,laptops,etc.)viaDropbox.Youget
freeupdatesforthelifeoftheedition.And,ofcourse,youcanalwayscomebackandre-downloadyour
bookswhenneeded.EbooksboughtfromtheAmazonKindlestorearesubjecttoAmazon'spolices.
LimitationsinAmazon'sfileformatmaycauseebookstodisplaydifferentlyondifferentdevices.Formore
information,pleaseseeourFAQatpragprog.com/frequently-asked-questions/ebooks.Tolearnmoreabout
thisbookandaccessthefreeresources,gotothebook'shomepage.
Thanksforyourcontinuedsupport,
AndyHunt
ThePragmaticProgrammers
Theteamthatproducedthisbookincludes:AndyHunt(Publisher), JanetFurlow(VPofOperations),
BrianMacDonald(ManagingEditor), JacquelynCarter(SupervisingEditor),
AdaobiObiTulton(DevelopmentEditor), PaulaRobertson(CopyEditor),
PotomacIndexing,LLC(Indexing), GilsonGraphics(Layout)
Forcustomersupport,pleasecontact
Forinternationalrights,pleasecontact


ForElsaandalltheprincesseswhoaregoingtochangetheworld.


TableofContents



Acknowledgments



Introduction
HowILearnedtoProgram(andWhyThatMatterstoYou)
HowYOUCanLearntoProgram
GettingHelp
WhatYouNeedforThisBook
WhatIsJavaScript?
What’sNewintheSecondEdition?
WhatThisBookIsNot
Let’sGetStarted!

1.

Project:CreatingSimpleShapes
Programmingwiththe3DECodeEditor
MakingShapeswithJavaScript
CreatingSpheres
MakingBoxeswiththeCubeShape
UsingCylindersforAllKindsofShapes
BuildingFlatSurfaceswithPlanes
RenderingDonuts(NottheKindYouEat)withTorus
AnimatingtheShapes
TheCodeSoFar
What’sNext

2.


Debugging:FixingCodeWhenThingsGoWrong


GettingStarted
Debuggingin3DE:TheRedX
Debuggingin3DE:TheYellowTriangle
OpeningandClosingtheJavaScriptConsole
DebuggingintheConsole
Common3DProgrammingErrors
RecoveringWhen3DEIsBroken
What’sNext

3.

Project:MakinganAvatar
GettingStarted
SmoothChunkiness
MakingaWholefromParts
BreakingItDown
AddingFeetforWalking
Challenge:MaketheAvatarYourOwn
DoingCartwheels
TheCodeSoFar
What’sNext

4.

Project:MovingAvatars
GettingStarted
BuildingInteractiveSystemswithKeyboardEvents

ConvertingKeyboardEventsintoAvatarMovement
Challenge:Start/StopAnimation
BuildingaForestwithFunctions
MovingtheCamerawiththeAvatar
TheCodeSoFar
What’sNext


5.

Functions:UseandUseAgain
GettingStarted
BasicFunctions
FunctionsthatReturnValues
UsingFunctions
BreakingFunctions
Bonus#1:RandomColors
Bonus#2:FlightControls
TheCodeSoFar
What’sNext

6.

Project:MovingHandsandFeet
GettingStarted
MovingaHand
SwingingHandsandFeetTogether
WalkingWhenMoving
TheCodeSoFar
What’sNext


7.

ACloserLookatJavaScriptFundamentals
GettingStarted
DescribingThingsinJavaScript
Numbers,Words,andOtherThingsinJavaScript
ControlStructures
What’sNext

8.

Project:TurningOurAvatar
GettingStarted
FacingtheProperDirection


BreakingItDown
AnimatingtheSpin
TheCodeSoFar
What’sNext

9.

What’sAllThatOtherCode?
GettingStarted
AQuickIntroductiontoHTML
SettingtheScene
UsingCamerastoCapturetheScene
UsingaRenderertoProjectWhattheCameraSees

ExploringDifferentCameras
What’sNext

10. Project:Collisions
GettingStarted
RaysandIntersections
TheCodeSoFar
What’sNext

11. Project:FruitHunt
GettingStarted
StartingaScoreboardatZero
GivingTreesaLittleWiggle
JumpingforPoints
MakingOurGamesEvenBetter
TheCodeSoFar
What’sNext

12. WorkingwithLightsandMaterials


GettingStarted
EmittingLight
AmbientLight
PointLight
Shadows
SpotlightsandSunlight
Texture
FurtherExploration
TheCodeSoFar

What’sNext

13. Project:PhasesoftheMoon
GettingStarted
TheSunattheCenter
GameandSimulationLogic
LocalCoordinates
Multi-CameraAction!
Bonus#1:Stars
Bonus#2:FlyingControls
UnderstandingthePhases
NotPerfect,ButStillaGreatSimulation
TheCodeSoFar
What’sNext

14. Project:ThePurpleFruitMonsterGame
GettingStarted
OutlinetheGame
AddingGroundfortheGame
BuildaSimpleAvatar


AddScoring
Gameplay
Improvements
TheCodeSoFar
What’sNext

15. Project:Tilt-a-Board
GettingStarted

OutlinetheGame
Bonus#1:AddaBackground
Bonus#2:MakeFire!
Challenge
TheCodeSoFar
What’sNext

16. LearningaboutJavaScriptObjects
GettingStarted
SimpleObjects
PropertiesandMethods
CopyingObjects
ConstructingNewObjects
TheWorstThinginJavaScript:Losingthis
Challenge
TheCodeSoFar
What’sNext

17. Project:Ready,Steady,Launch
GettingStarted
TheLauncher
Scoreboard


BasketsandGoals
Wind!
TheCodeSoFar
What’sNext

18. Project:Two-PlayerGames

GettingStarted
TwoLaunchers
TwoScoreboards
TeachingBasketstoUpdatetheCorrectScoreboard
SharingaKeyboard
ACompleteReset
TheCodeSoFar
What’sNext

19. Project:RiverRafter
GettingStarted
PushingandPullingShapes
RoughTerrain
DiggingaRiver
Scoreboard
BuildaRaftforRacing
ResettingtheGame
KeyboardControls
TheFinishLine
Bonus:KeepingScore
TheCodeSoFar
What’sNext

20. GettingCodeontheWeb


TheMighty,MightyBrowser
FreeWebsites
PuttingYourCodeonAnotherSite
TheCodeSoFar

What’sNext

A1. ProjectCode
Code:CreatingSimpleShapes
Code:PlayingwiththeConsoleandFindingWhat’sBroken
Code:MakinganAvatar
Code:MovingAvatars
Code:Functions:UseandUseAgain
Code:MovingHandsandFeet
Code:ACloserLookatJavaScriptFundamentals
Code:TurningOurAvatar
Code:What’sAllThatOtherCode?
Code:Collisions
Code:FruitHunt
Code:WorkingwithLightsandMaterials
Code:PhasesoftheMoon
Code:ThePurpleFruitMonsterGame
Code:Tilt-a-Board
Code:LearningaboutJavaScriptObjects
Code:Ready,Steady,Launch
Code:Two-PlayerReady,Steady,Launch
Code:RiverRafter
Code:GettingCodeontheWeb

A2. JavaScriptCodeCollectionsUsedinThisBook


Three.js
Physijs
Controls

Noise
Scoreboard.js
ShaderParticleEngine
Sounds.js
Tween.js



Bibliography
Copyright©2018,ThePragmaticBookshelf.


Earlypraisefor3DGame
ProgrammingforKids,SecondEdition
Thisbookhelpedmeexpandmyprogrammingknowledgeandintroducedmeto
3Dgamingconcepts,anditwasengagingatthesametime.
→ KeeleyL.,age13
Icrackedthisbookopenandhadflashbackstolaboriouslytypingoutgame
programsfortheCommodore64(ZuiderZeeforever!)andwasexcitedatthe
prospectofsharingthatsortofexperiencewithmyownkid.Thisletmedive
intoJavaScriptwiththerecklessabandonofmylong-lostyouthandimmediately
haveneatthingstoshow.FindingbooksthatIcanlearnsomethingfromisnot
terriblyhard,butfindingabookthatIcanlearnfromalongwithmykidis
invaluable.
→ RonDonoghue
Co-Founder,EvilHatProductions
Iam11yearsoldandhavebeenhomeschooledformyentirelife.Irecommend
thisbookasahomeschoolprogrammingcourseandforkidswhoenjoy
programmming.Thisbookisgoodforexperiencedprogrammersandnovice
programmerswhowanttodo3Dprogrammingrightaway.

→ BrysonS.,age11
Thisisagreathands-onbookforakidorevensomeonewithsome
programmingchops,whoisinterestedinmakingsmallgames.Itteachesyou
howtogetstartedwith3Dprogramming,andit’sreallyneatthatitshowshow
youcanbuildadecentgameinjustalittlebitoftime.
→ NickMcGinness
SoftwareEngineer,DirectSupply
Ithinkthisbookwouldteachkidsalotaboutprogramming3Dobjects.Ilearned


Ithinkthisbookwouldteachkidsalotaboutprogramming3Dobjects.Ilearned
aboutsomenewmathandprogramming.
→ Owen,age10
ChrisStromteacheskids3Dgameprogrammingwithsimpleyetpowerful
explanationsandexamples.Butifyou’reanadult,youcanlearnfromthisbook,
too.Idid!
→ RonHale-Evans
authorofMindPerformanceHacksandMindhacker
Thisisabrightandbreezytripthroughbasicgamecodingin3D,withmany
usefulandpracticaltipsonhowtoapproachprogramming.I’mconfidentmy
kidswilllearnalotfromit.
→ PaulCallaghan
Formereducator,nowwebdeveloper,andfatherofthreeboys
Ihadalotoffunwiththisbook.Ilikehowitalwayshintsatwhat’stocomesoI
wouldreallylookforwardtotheupcomingprojects.Theauthoralsocracked
jokesthatkidswouldunderstand.Ifeltasiftheauthorwastalkingtomeinreal
life,whichmadethebookmoreenjoyableandmadetheprojectseasytofollow.
Iwouldrecommendthisbooktoanyonewhoislookingforafunandeasyway
tolearncode.
→ CedricH.,age13



Acknowledgments


Iamnothingwithoutthestrengthofmyamazingwife,Robin,whohelpsinways
innumerable.Shewasthesoleeditorfortheearlyversionsofthebook.Despitea
fullloadofherown,shestillreadseverychapterandgivesinvaluablenotesand
suggestions.Shehelpedtorunthekidhackathons(OK,sherunsthem)that
aidedindevelopmentofthisbook.Andoh,yeah—she’sanawesomewifeand
mother.
Alsoabigthankstomykidsforservingastheprimaryguineapigsforthisbook.
Readerscanthankthemforforcingmetoremovetheboringstuffandmaking
thefunandinterestingstuffmoreso.Thanks,kiddos.
And,ofcourse,hugethankstomytechnicalreviewers.It’satoughtaskto
reviewabookfromakid’sperspective,butmyreviewersweremorethanupto
thetask.Innoparticularorder,theyareAnaB.,DougC.,BrysonS.,CedricH.,
KeeleyL.,PaulCallaghan,RobDonoghue,KevinGisi,RonHale-Evans,Brian
Hochgurtel,BrianHogan,ChaimKrause,NickMcGinness,JamesSterrett,and
JeremySydik.
ThisbookwouldnotexistwithoutthegreatworkofRicardoCabelloMiguel,
affectionatelyknownas“Mr.doob.”Ricardoistheprimaryprogrammerbehind
Three.js,the3DJavaScriptlibrarythatweuseinthisbook.Healsowrotethe
originalimplementationofthe3DECodeEditorthatweuse.Thisbookwould
besignificantlylesswithouthisamazingtalents.ThanksalsotoChandlerPrall
forhisworkonthePhysijsphysicsengine,ofwhichwemakeextensiveuse.
Last,butnotleast,manythankstothefolksatThePragmaticProgrammersfor
believinginthebookandhelpingmerealizeitsfullpotential.Specialthanksto
myeditor,Adaobi.Asecondeditionisnoeasytask,butshekeptmefocusedand



myeditor,Adaobi.Asecondeditionisnoeasytask,butshekeptmefocusedand
helpedhonethenarrativeinwaysthatwereunexpectedlyrewarding.
Copyright©2018,ThePragmaticBookshelf.


Introduction


Welcometotheworldofprogramming!
Iwon’tlie;itcanbeafrustratingworld(itmakesmecryatleastonceaweek).
Butit’stotallyworththepain.Yougettomakethisworlddowhateveryou
want.Youcanshareyourworldwithothers.Youcanbuildthingsthatreally
makeadifference.
Thisbookthatyouholdinyourhandsisagreatwaytogetstartedwith
programming.Why?Becausethisbookbelievesthebestwaytolearn
programmingisbyplaying.Oh,thereareafewchaptersthatdescribe
fundamentals,butweonlygettothoseafterhavingfun.Sowejumprightinto
someprettycool3DanimationinChapter1.
Thisisgoingtobeablast!


HowILearnedtoProgram(andWhyThatMattersto
You)
WhenIwasakid,Icopiedcomputergameprogramsoutofbooks.Thiswasa
longtimeago,soIboughtbookswithnothingbutcomputercode,andtypedit
intomycomputer.Ittookawhile,andIhadnoideawhatIwasdoingatfirst.
Eventually,Istartedtorecognizethings.AndthenIstartedtochangesomeof
theprograms—littlethingsatfirst—toseewhathappened.ThenIstartedmaking
biggerchanges.EventuallyIgotprettygoodatitandcouldevenwritemyown

programs.
Ihopethatthisbookwillletyoudothesame,butwithoneimportantdifference:
I’llexplainwhat’sgoingonsoyouwon’thavetoguessquiteasmuch.


HowYOUCanLearntoProgram
Everybodyisdifferent.Everybodylearnsdifferently.
Becauseofthat,thereareatleastthreedifferentwaysthatyoucanlearnfrom
thisbook:
1. Playwithcoolstuff,thenreadanoccasionalchapteronfundamentals.
2. Learnthebasics,thenmakesomecoolstuffwithwhatyouknow.
3. Justtypethecode(likeIdidwhenIwasakid).
Youchoosewhichworksbestforyou!
Ifyouwanttoplayfirst(thefirstoption),startwithChapter1andthengoin
orderthroughtherestofthebook.You’llmostlyworkongamesandsimulations
inprojectchapters—chapterswhosetitlesstartwiththeword“Project”—
followedbyoccasionalchaptersonfundamentalskills.Ifyou’renotsurewhich
optionisbest,choosethisone.ThisisthewayIwishIcouldhavelearned.
Ifyou’rethekindofpersonwholikestounderstandfundamentalsbefore
buildingbiggerthings(thesecondoption),thenreadthe“essentials”chapters
first—anychapterwithout“Project”inthetitle.There’sstillplentyofcodingin
themand3Dfuninsomeofthem.Comparedtootherprogramminglanguages,
thecoreofJavaScriptisfairlysmall.Youcanlearn80–90percentof
JavaScript’scorejustbyreadingthosechapters.Beingabletouseitwellis
anotherthing—whichiswherethe“Project”chapterscomein!
Ifyoujustwanttocode(thethirdoption),thenfliptoAppendix1,ProjectCode.
Allthecodefromallthegamesisthere.Ifyougetstuckwithsomeofthe
coding,thenfliptothechapterthatthecodecamefromforadeeperexplanation.
ThisishowIlearned,andIturnedoutmostlyOK!
Nomatterwhichoptionisbestforyou,there’sonerule:alwaystypethecodein

byhand.Thisismuchslowerthancopyingandpasting.You’remuchmore
likelytomakemistakestypingcodeinyourself.


Goingslowandmakingmistakesisthepoint!

Typingcodebyhandmakesyouthinkmoreaboutwhatyou’retyping.You
mightbelievethatyoucanlearnjustaswellbyreadingandthencopyingand
pasting,butthisis100percentnottrue.Evenifyou’vebeenprogrammingfor50
years,youshouldnevercopyandpastecode.Typinggivesyoutimetothinkand
tounderstandthecodeyou’readding.Thatisfarmoreimportantthangettingit
donequickly.
Makingmistakesispartofprogramming.Beingabletofixbrokencodeisjustas
importantasbeingabletoprogram.Somakemistakes.Itwillbehardand
frustrating.Anditwillbeworthit.
Thismeansthatwe’vereachedthefirsttipinthebook!Especiallyimportanttips
andguidelinesarehighlightedthroughoutthebook.Payattentiontothem
becausetheycanreallymakeadifferenceasyouexplorethisworld.


AlwaysTypeCode/NeverCopyandPaste!
Goodprogrammersalwaystypecodebyhand—they
nevercopyandpastecode.Writinggoodcomputer
programsismuchmoreimportantthanwritingthem
quickly.Goodprogrammingmeansthinkingabout
thecodethatyoucreate.Itmeansunderstanding
code.Sotypeitout!

Onemorething:ifyougetstuck,youcanalwaysgethelp!



GettingHelp
Everyprogrammerneedshelp.Ifyou’veneverprogrammedinyourlife,you
willneedhelp.Ifyou’vebeenprogrammingfor50years,you’llstillneedhelp.
Thetworulesforaskingforhelp:
1. Trytofigureitoutyourselfatfirst.
2. Don’tbeafraidtoaskforhelp.
Knowingaprogramminglanguagereallywellisnotthemostimportantskilla
programmercanhave.Themostimportantskillisproblem-solving.Knowing
everythingaboutacomputerlanguagedoesnotmeanthatyou’llcreate100percentproblem-freecode.Ithelps,butproblemsstillhappen.Alot.Sotryto
figureoutproblemsonyourown.Evenifyoucan’tsolveaproblem,you’restill
improvingyourproblem-solvingskills.
Speakingofproblem-solvingskills,Chapter2,Debugging:FixingCodeWhen
ThingsGoWrongistheplacetogetstarted.Thatchapterdescribescommon
mistakes,howtosolveproblemsusingthecodeeditorandthebrowser,andhow
torecoverwhenthingsgoreally,reallywrong.


Don’tSkipChapter2!
Problem-solvingiscrazyimportant,sobesureto
readChapter2.
Nomatterhowyoulearn,thedebuggingskills
describedinChapter2aremustreading.Itmight
seemlikeyoucanskipthatstuff,butskippingthat
chapterislikeplayingsportswithoutpadsordriving
withoutaseatbelt.Thingsmightseemfinewithout
thesafetyofdebuggingskills.Rightupuntilthe
pointthatsomethinggoesreallywrong.



Itis100percentOKifyoucan’tfigureoutaproblemonyourown.Iamhappy
tohelp.Thisbookhasitsownwebpagewhereyoucanfindallthecodeforthis
book,aswellasthebook’scommunityforum.[1]Ifyougetstuck,postaquestion
totheforum.Ialmostalwaysanswerwithin24hours.Justbesuretotellmehow
you’vealreadytriedtosolvetheproblem—otherwisethat’sgoingtobemyfirst
questiontoyou.
Butplease,Iwantyoutodowell.Askquestions.Usetheforum.Let’scode!


WhatYouNeedforThisBook
You’llneedtheGoogleChromewebbrowserandarelativelynewcomputer.
That’sit!
Notallwebbrowserscangeneratethecool3D-gamingobjectsthatwe’llbuild
inthisbook.Togetthemostoutofthebook,youshouldinstalltheGoogle
Chromewebbrowseronyourcomputer.[2]Otherwebbrowserswillwork,but
someoftheexercisesinthisbookrelyonfeaturesavailableonlyinGoogle
Chrome.
Anymoderncomputer(fromthepastfiveyears)withGoogleChromeinstalled
willbesufficient.Tobesure,youcantestyourcomputer’scapabilitiesby
visitingtheGetWebGLsite.[3]Ifthatsitedoesn’ttellyouthatyourbrowser
supportsWebGL,thenyoumayhavetotryanothercomputer.


WhatIsJavaScript?
Therearemany,manyprogramminglanguages.Someprogrammersenjoy
arguingoverwhichisthebest,butthetruthisthatalllanguagesofferuniqueand
worthwhilethings.
InthisbookweusetheJavaScriptprogramminglanguage.Weprogramin
JavaScriptbecauseit’sthelanguageoftheweb.It’stheonlyprogramming
languagethatallwebbrowsersunderstand.IfyoucanprograminJavaScript,not

onlycanyoumakethekindsofgamesthatyou’lllearninthisbook,butyoucan
alsoprogramjustabouteverywebsitethereis.


×