关闭

关闭

关闭

封号提示

内容

首页 GML.pdf

GML.pdf

GML.pdf

上传者: zpw759 2011-12-05 评分 0 0 0 0 0 0 暂无简介 简介 举报

简介:本文档为《GMLpdf》,可适用于游戏领域,主题内容包含TrollsplattererGameMakerLanguageByTrollsplattererAbstractHellothereThistut符等。

TrollsplattererGameMakerLanguageByTrollsplattererAbstractHellothereThistutorialismeanttobeanintroductiontoGMLprogramminginGameMakerGameMakerisaprogramtocreategamesItiseventdriven,whichmeansthateachstepofthegame,asequenceofeventsistriggered(ieplayerpresseskeyboardormouse)Eacheventcanexecutecommands(iemoveobjects)ThesecommandsareprogrammableGMhastwodifferentwaysofprogrammingthesecommands:–DDactions:simpleDragandDropitems,providingfillinstosimplifyprogramming–GMLcode:pureprogramminglanguageThistextexplainsthebasicsofGMLprogrammingDonotexpecttobecomeanoviceprogrammer,usingonlythistext,butafterreadingit,youshouldbeabletoexpandyourknowledge,usingtheGMhelpfileandotherpeoplesexamplesTrollsplattererGMLvsDD“What'stheadvantageofGMLoverthedraganddropinterface”,onemayaskYoucandoeverythingyouwantwithDD,can'tyouI'llshowyousomeadvantagesofGMLCopypasteYoucancopyDDactionswithinthesamegamefile,butyoucan'tcopythemtoadifferentfileYouhavetomergethegamestogettheactionsofanobjectfromadifferentfileGMLispuretext,soyoucaneasilycopyitfromonefiletoanotherAsecondreasonwhyyoumightwanttocopycode,iswhenyouwanttoshowyourcodetosomeoneelse,iewhenyouwantsomehelpYoucaneasilycopypastetheGMLcodeandotherpeoplecaneasilymodifyittotellyouwhatyou'redoingwrongIfyouwanttoshowyourDDcode,you'llhavealotmoretroubletryingtoshowyourcodeandpeoplewillhaveahardtimetryingtoanswerclearlyUploadingyoursourcefile(gmk)isnotasafewayeitherClaritySomepeoplemayobjecthere,statingthatGMLisalotmorecomplexthanDD,soitcanneverresultinclearersourcecodeI'mnottalkingaboutasequenceoftwoorthreeactions,herethoughIfyoueverhadtoaddmorethanactionstoasingleevent,you'llknowthattheDDstructuretendstolooseitsclarityImaginewhatit'lllooklikeifyourequireonehundredactionsTheonlywaytoaddsomestructureistouseStartBlockandStopBlockactionsYoucanalsoaddsomecomments,butonlysinglelinesinseparateactionsInGML,youcanuseindentation,spacingandmultilinecommentstoclarifythecodeYoucanalsoaddcommentsinthesamelineasthecodeThisresultsinamorereadablecode,soit'seasierforyourselftofindcertainpartsandforotherpeopletounderstandwhatyou'retryingtodoRememberthatyoumaynotbeabletoremebereverythingaboutyourcodeyourself,socommentingisquiteusefulSpeedAsyougettoknowGML,you'llbeabletoproceedfasterthanyoucouldeverbe,usingtheDDinterfaceDDrequiresaconstantinteractionofthemouseandthekeyboard:draganaction,fillthefillins,clickOKWithGML,youonlyhavetouseoneactionforeveryevent:thecodeactionAfterselectingthisaction,youonlyneedyourkeyboardMoreoptionsDDislimitedSomeGMfunctionalitiesrequireGML,suchasDandmultiplayeronlinegamesSomeDDactionsareunavailableinGMlite,butcanbeachievedusingcode(iesettingthecursor)GMLcontainsagreatnumberoffunctionstocalculatemathematicalmattersortocheckforcollisionatpointsorwithinregions,forexampleYoucanforcetheseintheDDactions,usingtheCheckVariableaction,ortheTestExpressionaction,butifyou'recapableofthat,youshouldbeTrollsplatterercapableofusingGMLtoo,it'sonlyasmallstepManyfunctionshavethesameresultasaDDaction,butmostprovidemoreoptions(arguments)andreturninformationonwhethertheactionsucceededInsightIfyouuseaDDaction,youneverreallyknowwhat'shappeningbehindthescenesIfyouusetheMoveFixedaction,yousetthemovementoftheobjectButwhatdoesthatmeanWhichvariablesareinfluencedGMLencouragesyoutousethevariablesdirectlyIfyouwanttostopthemovement,yousetthevariablespeedtoYoucanalsochoosetousefunctionswiththesameresultsastheDDactions,ifyoudon'tknowhowtomakeithappenyourself,usingvariablesReusabilityIfyouknowGML,youcanwritescriptsScriptsarefunctionsofyourownSupposeyouregularlyneedtousethesamecode,youcanwriteitinascriptandexecutethisscriptineveryeventwhereyouneedthiscodeThisrequireslessworkandit'seasiertomodifyitlateronThecodeislocatedatasingleplace,soyoudon'thavetochangeitineveryeventDebuggingLargechunksofcodehaveahighchanceofcontainingflawsandit'shardtofindthesewithoutanyhelpYoucanusethedebugmodetocheckthestateofthevariablesineveryinstance,butthisonlyshowsthestatesinbetweeneverystepItisimpossibletocheckthevalueofavariableatacertainlocationwithingacertaineventInGML,youcanusemessagestoshowthevalueofavariableatapreciselocationinthecodeYoucanalsocommentcertainpartsofcodetocheckwheretheerrorsoccurOtherprogramminglanguagesLastbutnotleast,knowingGMLisusefulifyou'replanningonlearningsomeotherprogramminglanguagelateronGMLisamixtureofmanydifferentprogramminglanguagesOnceyouknowyourwayinGML,thegateisopenforyoutotryandlearnsomeotherlanguage,suchasC,C,C#,Java,VisualBasic,PHPGMLisafunwayoflearningsomethingyoumaywellbecapableofusinglateronComputerswillkeepgettingastrongergriponoureverydaylife,sothere'snoharminlearninghowtohandlethemTrollsplattererIntroductiontoGameMakerTounderstandthishelpfile,you'llhavetoknowthebasicsofthewayGMworksI'llusekeywordsyouhavetounderstandinordertoknowwhatI'mtalkingaboutThefilecontainsasmallindexatthebottom,soifyoudon'tknowacertainword,itmaybeexplainedintheindexAmorethouroughexplanationmaybefoundintheGMhelpfileorusinggoogleIfyoualreadyknoweverythingaboutobjects,instancesandvariablesyoucanskipthischapterStepsAgameisexecutedinstepsInbetweeneachstep,GMrecalculateseverythingandattheendofthestep,thescreenisdrawnTheperiodofonestepdependsonthespeedoftheroomTheroomspeedisexpressedin“stepspersecond”,soifyousettheroomspeedto(defaultvalue),therearestepsineverysecondAllotherspeeds(objectspeed,animationspeed)arerelativetotheroomspeed,soifyougiveanobjectaspeedof“”,it'llmoveatpixelspersecond(pixelsxstepspersecond)EventsGMiseventdrivenThatmeansthateverythingthathappens,triggersaneventObjectscanreacttotheseeventsSomeexamplesofevents:–RoomStart:thefirststepinthecurrentroom–Collision:thecurrentinstancehitsthespriteofadifferentobject–KeyboardPressF:theplayerpressedthe“F”buttonjustnow–KeyboardF:theplayerispressingthe“F”buttonThesequenceoftheseeventsisthis:–Beginstepevents–Alarmevents–Keyboardevents–Mouseevents–Stepevents–(nowallinstancesaresettotheirnewpositions)–Collisionevents–Endstepevents–Drawingevents–(nowthescreenisdrawn)(source:GMhelpfile)ResourcesResourcesarethedifferentelementsofthegame:–sprites(imagesandanimations)–sounds–scripts–objects–TrollsplattererActionsIfaninstancesensesanevent,itcanexecuteasetofactionsActionsinfluencethebehaviourofthecurrentinstance,oradifferentinstanceActionscancausemovement,changementofsprite,creationofnewinstancesObjectsObjectsarethedefinitionofanelementofthegameTheycandefinewalls,characters,water,invisiblecontrolelementsInstancesWhenyoucreateacharacterobject,wecallthecharacteraninstanceofthischaracterobjectSoanobjectcanhavemultipleinstancesinthegame(iewalls:onlyoneobject,butyouusemanywallsinyourrooms)Infact,whenyourgameisrunning,therearenoobjectsinthegame,onlyinstancesVariablesThesearelittlememorycellsyoucanusetostoreinformationTheyhaveanameandavalueAnexampleisthehealthvariableItcontainsyourcurrenthealthTheyoyogamessitecontainsaWIKIaboutvariables:http:wikiyoyogamescomindexphpVariablesTrollsplattererUsingGMLcodeExecutingcodeIfyouwanttoruncodeatacertainevent,youhavetoaddanactionthatexecutesGMLcodeGMhastwodifferentwaysofaddingcodeCodeActionThecodeactionislocatedinthecontroltaboftheactionsSelectitanddragitintotheactionsfieldThiswillopenawindowInthiswindow,youcanentercodeThecodewillbeexecutedwhenthecodeactionisreachedduringthegameYoucanmixDDactionswithcodeactionsScriptsScriptsareresourcesthatcontainreusablecodeWithscripts,youcancreateyourownfunctions,usingGMLcodeExamplesofexistingfunctionsare“pointgetdistance()”and“gamesave()”Youcouldmakeafunction“destroyallenemies()”Theadvantagesoverthecodeactionare–Youcanexecutethesamecodeindifferenteventsandobjects,yetthecodeitselfisonlylocatedinthescript,soyouonlyhavetochangethescriptifyouwanttomodifythecode,younolongerhavetomodifyeveryobject–Youcangiveargumentstothescript,tomanipulateitsbehaviourForexample,thefunction“gamesave("savegamets")”savesthegamewiththename“savegamets”TheargumentyouusetellsthefunctionwhatnametouseforthefileScriptsworkexactlythesamewayIfyouwanttorunascript,youcanusetheExecuteScriptactioninthecontroltab,oryoucanrunthescriptwithcodeThesyntaxforrunningitusingcodeisthis:myscriptname(arg,arg,arg,arg)orscriptexecute(myscriptname,arg,arg,arg,arg)We'llgettoseemoreaboutscriptsonceIexplainedthebasicsofcodeBasicprogramminginGMLWhatdoesGMLlooklikeYou'vecertainlyseencomplicatedexampleswithmanylinesandstrangesymbolsI'llkeepitsimplehere,intimeyoumaybeabletowritecomplicatedcodeyourselfInthischapterI'llgiveyouashortsummaryofthepossiblecommandsinGMLTrollsplattererNotethattheGMLcompiler(interpretesyourcode)isverylooseaboutsyntaxTherearemanydifferentwaysofwritingthesamecommandHere'sanexample(don'tworryaboutunderstandingityet):ifhealth<=thengameend()elseshowmessage("Argl")isequaltothecodeif(health<=){gameend()}else{showmessage("Argl")}Iusemyownwayofwritingcode,whichisthesecondexampleYoumaysometimesfindcodesamplesotherpeoplewrotethathaveanentirelydifferentstructureThatdoesn'tmeanthatpieceofcodeiswrongGMLallowsthisvarietyinstylesandit'suptoyouwhichstyleyouchooseMystylehastheserules:–Astatementendswitha“”character–Everyblockofcodewithinanotherblockhasanadditionalindentation(tab)–Ifablockofcodeonlycontainsonestatement,theparenthesesmaybeomitted–Strings(characters)areboundedbydoublequotes,unlessadoublequoteispartoftheletters–Aconditioninanif(orlikewise)statementisboundedbyopeningandclosingparentheses–Functionsarerunbytheirname,followedbytheargumentsbetweenparenthesesVariablesTostoreavalueinavariable,youusethe“=”characterThesyntaxofthiscommandis:variablename=valueAfterthiscommand,thevariablewiththenamevariablenamewillcontainthevalue“value”Asecondwayofstoringsomethinginavariable,isusinganexpressionasavalue:variablename=expressionAnexpressioncanbeanything,reallySomeexamplesare:**(mod)variablename*random(variablename)ExpressionscancontainvariablesandfunctionsFirsttheexpressionisinterpretedandthefunctionsareexecuted,sotheirresultscanbeusedThentheresultingvalueisstoredinthevariablevariablenameAcommonproblemwithvariablesisthecreationGMcreatesthevariablewhenitissetforthefirsttimeYoucan'tusethevalueofavariablebeforeithasoneThemistakeusuallyoccurswhentheprogrammertriesthisstatement:myvariable=increasethevalueofthevariablemyvariableToincreasethevalueofavariable,ithastohaveavaluetobeginwithThiscodeisinfacttheabbreviationof:myvariable=myvariableThisstatementclearlyshowsthatthevariablehastohaveavaluebeforeitisexecutedThat'swhyitisagoodideatoseteveryvariabletoaninitialvalueinthecreationeventoftheobjectTrollsplattererFunctionsGMcontainsahugeamountofpredefinedfunctionsSomeonlyreturnavalue,someexecutecommandstoinfluenceyourgameItwouldtakemefartoolongtogiveadescriptionofeveryfunctioninGM,butallthefunctionsaredescribedintheGameMakerHelpFileAlistofallthefunctionscanberetrievedbypressingScripts=>ShowBuiltinFunctionsFunctionshavearguments,whichdecidetheresultofthefunctionsAsafirstexample,we'llusethefunctionrandom(arg)ThisfunctionreturnsarandomrealvaluebetweenandthevalueofargYoucanchoosethemaximumvaluebyenteringavalueasargumentvariablename=random()wouldstoretheresultofthefunction(anumberwiththevalue,)inthevariablenamedvariablenameAsecondexampleisthefunctionmotionset(dir,speed)Theargumentsinthisfunctiondecidethemotionoftheinstanceinwhichthiscodeisexecutedmotionset(direction,)stopsthemotionoftheinstance,butkeepsthecurrentdirectionsetmotionset(,speed)setsthedirectiontodegreesandkeepsthecurrentspeedintactArgumentscanalsocontainexpressions,butthesedecreasethereadibilityofthefunction:motionset(floor(directionrandom()–),speedrandom()–)Modifiesthespeedanddirectionrelativelywitharandomvalue,butitmaybecomeunclearwhichvalueistheargumentofwhichfunction,asfunctionscanhaveuptoargumentsAnalternativeisusingselfdefinedvariablestostoretheresultoftheexpressions:definetemperaryscriptvariablesvarnewdirection,newspeedremembertheresultoftheexpressionsinthesevariablesnewdirection=floor(directionrandom()–)newspeed=speedrandom()–usethevariablesasargumentsforthefunctionmotionset(newdirection,newspeed)Theresultisalongercode(evenifyouremovethecomments),butit'seasiertoreadandit'seasiertoseemistakesandmakeimprovements,andasyousee,it'seasiertoaddcommentsCommentsCommentsaretextmessagesyouwritetoclarifyyourcodeThiscanbeusefultoexplainyourcodetoothers,butit'salsohelpfulifyouneedtomodifyyourcodelateronYoucanalsodisactivateasectionofcodebycommentingit,soyoudon'thavetodeletethecode,butitisn'texecutedeitherYoucanaddaninitialcomment,atthestartofthecode,inwhichyouexplainthepurposeofthecodeandtherequiredargumentsTherearetwowaysofaddingcomment:aMultilinecommentsWithmultilinecomments,everythingthat'slocatedbetweenthestartdelimitor(*)andtheenddelimitor(*)isseenascommentandisnotexecutedduringthegameTrollsplatterermyvariable=*addthecommentshere*or*sometextsomemoretextevenmoretext*orevenmyvariable=*somecomments*bSinglelinecommentsSinglelinecommentsstartwithtwoslashes()Thepartofthelinethat'sbehindthesecharactersisseenascommentaddcommentshereormyvariable=thisisacommentConditionsManycommandsonlyneedtobeexecutedifacertainconditionistrueForexample,thegamehastostopifthehealthofthemaincharacterreachesIncode,youcanhandlethisusingtheIFexpression:if(condition){codeblock}else{codeblock}TheconditionisevaluatedTheresultingvalueofthisexpressionshouldbetrueorfalseSomeexamplesofconditionsare:>(islargerthan)x<(horizontallocationissmallerthan)distancetoobject(objtroll)<=(issmallerthanorequalto)Iftheexpressionistrue,thecodeblockbetweenthefirsttwobracketsischosenOtherwise(false)thesecondblockisexecutedThesecondpartisnotobligatory,soifyoudon'twantanythingtobeexecutediftheconditionisfalse,youcanusethisstructure:if(expression){codeblock}Ifacodeblockonlycontainsonesinglecommand,theparethesiscanberemoved:if(expression)SinglecommandSomepeoplefindthisconfusing,butifyouuseproperindentationitdoesn'tresultinunclearcodeTrollsplattererI'llgiveashortexampleofaconditionalcode:Supposeyouwouldwantacharacter(objchar)toturnaround(turndegrees)andspeedupifitgetstooclose(pixels)toatroll(objtroll):CodeactionintheStepeventofobjectobjchar:if(distancetoobject(objtroll)<)ifthetrollgetstooclose{direction=directionrotatespeed=speedincreasespeedby}Youcanusethesecomparisonsinexpressions:<smallerthan<=smallerthanorequalto==or=equalto!=or<>notequalto>largerthan>=largerthanorequaltoYoucanalsocombinetwoormorecomparisons,usingthekeywordsand(alternative:)andor(alternative:||)Supposeyouonlywantthecharactertorunawayfromthetrollifitistooweaktofighthim(localvariableHPissmallerthanorequalto),thenthepreviouscodewouldbecome:if(distancetoobject(objtroll)<andHP<=){direction=directionrotatespeed=speedincreasespeedby}LoopsSometimesyoumaywantcertainblocksofcodetoberepeatedanumberoftimesWithloops,youcanrepeatablockofcodeuntilagivenconditionisfalseYoucancreateloopswiththewhilestatementSyntax:while(condition){codeblock}Here'sasimpleexampleofhowtocreateinstancesofobjectobjtroll:initiateacountervariablecounter=repeatuntilthecounterreachesavaluethat'shigherthanwhile(counter<=){createaninstanceofobjectobjtrollatlocation(,)instancecreate(,,objtroll)increasethecounterbycounter=counter}Noticewhatwouldhappenifyouwouldforgetthelaststatement(counter=counter)Theresultwouldbeaneternalloop,whichwouldcreatesomanytrollsyourgamewouldcrashThat'swhyyouhavetowatchoutwhenyou'reusingloopsMakesuretheconditionbecomesfalseintimeThereisaspecialkindofloop,whichcanbeusedtorepeatablockofcodeacertainamountofTrollsplatterertimes,withoutusingavariabletocountupordownsyntax:repeat(number){codeblock}example:repeattimesrepeat(){createaninstanceofobjectobjtrollatlocation(,)instancecreate(,,objtroll)}ArraysVariablesarethemostbasicelementsofprogramming,sotheyareusedalotTheproblemisthatavariablecanonlycontainonevalueatatimeIfyouwanttostorealistofrelatedvalues,ietheamountofbulletsforthedifferentguns,youcouldmakeaseparatevariableforeverytype

用户评论(0)

0/200

精彩专题

上传我的资料

每篇奖励 +2积分

资料评价:

/24
0下载券 下载 加入VIP, 送下载券

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部