453
Designing Games with Game Maker Version 8.0 Written by Mark Overmars The documentation for Game Maker is divided into four parts: Using Game Maker This section describes the basic use of Game Maker. It explains the global idea behind the program and describes how to add sprites, background and sounds and how to define objects with events and actions and how to add them to rooms. The following topics exist in this section: Introduction Installation Upgrading to the Pro Edition Getting Started The Global User Interface Defining Sprites Sounds and Music Backgrounds Defining Objects Events Actions

Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

DesigningGameswith

GameMakerVersion8.0

WrittenbyMarkOvermars

ThedocumentationforGameMakerisdividedintofourparts:

UsingGameMaker

ThissectiondescribesthebasicuseofGameMaker.Itexplainstheglobalideabehindtheprogramanddescribeshowtoaddsprites,backgroundandsoundsandhowtodefineobjectswitheventsandactionsandhowtoaddthemtorooms.

Thefollowingtopicsexistinthissection:

IntroductionInstallationUpgradingtotheProEditionGettingStartedTheGlobalUserInterfaceDefiningSpritesSoundsandMusicBackgroundsDefiningObjectsEventsActions

Page 2: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

CreatingRoomsDistributingyourGame

Advanceduse

ThissectiondescribesthemoreadvancedaspectsofGameMaker.Itdealswithpaths,fonts,timelines,scripts,andtechniquesforcreatingtiledroomsandusingviewsinrooms.

Thefollowingtopicsexistinthissection:

AdvancedUserInterfaceMoreaboutSpritesMoreaboutSoundsandMusicMoreaboutBackgroundsMoreaboutObjectsMoreActionsConstantsTriggerEventsIncludingFilesMoreaboutRoomsFontsPathsTimeLinesScriptsExtensionPackagesExportingandImportingResources

Polishingyourgame

Thissectiondealswithhowtoturnyourprojectintoafinishedgame.Itdescribeshowtoaddhelpinformationtoyourgame,howtosetthevariousoptionsforyourgameandhowtocreatestand-alonegamesthatyoucandistributetoothersandcanberunwithouttheneedforGameMaker.

Page 3: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thefollowingtopicsexistinthissection:

GameInformationGlobalGameSettingsSpeedConsiderations

TheGameMakerLanguage

GameMakercontainsabuilt-inprogramminglanguage.Thisprogramminglanguagegivesyoumuchmoreflexibilityandcontrolthanthestandardactions.ThislanguagewewillrefertoasGML(theGameMakerLanguage).InthissectionwedescribethelanguageGMLandwegiveanoverviewofallthe(closeto1000)functionsandvariablesavailabletocontrolallaspectsofyourgame.

Thefollowingtopicsexistinthissection:

LanguageoverviewComputingthingsGameplayUserinteractionGamegraphicsSoundandmusicSplashscreens,highscoresandotherpop-upsResourcesChangingresourcesFiles,registry,andexecutingprogramsDatastructuresCreatingparticlesMultiplayergamesUsingDLL's3DGraphics

Page 4: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

WhatisNew

Version8.0ofGameMakerhasalargenumberofimprovementsoverversion7.0.Belowthemostimportantchangesaredescribed.

Incompatibilities

Textsplashscreenscannolongershowimages.However,websplashscreenshavebeenaddedthatcanshowfullhtmldocumentswithimages,etc.

Anumberofchangeshavebeenmadetothefunctionsrelatedtospriteandbackgroundresources.ThisisduetothefactthatGameMakerusesacompletelynewmechanismfortheseresources.Ifyourgameusesalotofcallstofunctionsthatloadorsaveimageresourcesontheflyyouarestronglyrecommendedtokeepusingtheoldversion7.0forthatgame.

Ifyouuseextensionpackagesyouwillhavetoreinstallthem.

Somechangeshavebeenmadetothetimelinemechanismthatcanleadtoincompatibilities.Inparticular,assigningatimelineandstartingitarenowtwoseparatethings.

Animportantbughasbeensolvedinwhichcollisioneventswhereexecutedtwiceiftwoobjectshavecollisioneventswitheachother.Somegameshowevermighthavereliedonthisbugand,hence,mightnolongerfunctioncorrectly.

News

GameMakernowdefaultshowsaNewspagewhenitisstarted.Herenewversionswillbeannounced,newresourceswillbeindicated,thereisinformationaboutcompetition,andgamedesigntipsandtricks.Newsis

Page 5: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

shownonlyonceaday.IntheProEditionthiscanbeswitchedoff.YoucanalwaysaccessthenewsthroughtheHelpmenuandyouareencouragedtoregularlycheckthenewsforimportantinformationaboutGameMaker.

Tutorial

GameMakernowhasastandardbuilt-intutorialforbeginners.Itisshowninapanelattherightofthescreen.Experienceduserscanindicatethattheydonotwanttoseethetutorialanymore.Toaccommodateforthetutorialpanel,GameMakerisnowdefaultstartedinfullscreenmode.Itdoeshoweverrememberitssettingssochangingitoncetowindowedmodewillfromthatmomentonstartitinthatmode.

Alpha-blendedbackgroundsandsprites

ThenewversionGameMakerusesbackgroundsandspriteswithalpha(transparency)channels.Thismakesitpossibletocreateandusemuchnicersprites.PNGfileswithsuchinformationarenowcorrectlyloaded.Thespriteandimageeditorhavebeencompletelyrewritten,includingmanynewdrawingoptionsandeffects.Anewspritefileselectorwasaddedthatshowstheanimationsinthesprites.Alsowebundlealargenumberofhigh-qualityspriteswithGameMakerthatyoucanuseforfreeinyourgames.

Enhancedcollisionchecking

Younowhavemorecollisioncheckingoptions.Forexample,youcanindicatethatcollisionsshouldbewithanencloseddiskandyouhavebettercontrolovertheboundingbox.Thesub-imageofthespritecanhaveacombinedmaskandyoucansetthedependenceonthealphatransparencyvalue.

Page 6: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Splashscreens

Anewfunctionsplash_show_web(url,delay)hasbeenaddedthatcanbeusedtoshowwebpagesassplashscreens.Youcanalsouselocalhtmlpagesforthis.Thisallowsforapowerfulmechanismtoe.g.createhelppages.Aclosebuttonisaddedtothesplashscreens.Alsoanumberofnewactionshavebeenaddedtoshowthedifferenttypesofsplashpagesandtochangesplashsettings.(TheoldShowVideoandWebpageactionshavebeenremovesasthenewactionsincludethem.Theywillthoughstillworkinoldgames.)

Triggerevents

Anewtypeofeventhasbeenintroduced:Triggerevents.Triggereventsyoucanspecifyyourself.Yougivethemanameandacondition,writteninGML.Afterthistheycanbeusedinallobjects,justlikeotherevents.WiththisyoucaneasilyextendthefunctionalityofGameMaker.

Timelines

Thetimelineshavebeenextended.Thepropertyformhasadditionalbuttonstoe.g.spreadoutthemomentsandtodeleteorduplicaterangesofmoments.Timelinescannowbepausedandrestartedandtheycanevenbeplayedbackwards.Alsotheycannowloopautomatically.

Importingandexportingresources

Thepossibilitytomergegameshasbeenreplacedbyamuchmoreextensivesystemtoimportandexportresources.Theusercanindicatewhichresourcestoexporttoafile(.gmres).Nexttheycanbeimportedinadifferentgame.Inprincipleonlyoneresourcecanexistforeachname.Whenthereisanameconflictwhenimportingtheusecanspecifytokeeptheoriginal,replaceanyway,taketheonethatismostrecently

Page 7: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

changed,orkeepboth(notrecommended).Tobeabletodothethirdoption,allresourcesnowkeeptrackofwhentheywerelastchanged.

Rewrittenscriptandcodeeditor

Thebuilt-inscript/codeeditorhasbeencompletelyrewritten,makingitaloteasiertowritecode.Forexamplethereispop-upfunctionnamecompletion,argumenthelp,matchingbrackets,improvedcolorcoding,linenumbers,on-the-flyerrorchecking,codesnippets,andasophisticatedfindandreplacefunctionality.

Speedimprovements

Thespeedofgamesthatusecodehasbeenconsiderablyimproved.Aspeed-upofupto100%issometimespossible.Alsotheloadingtimeforgamesisoftenconsiderablyimproved.Alsowhenrunningastand-alonegame.

Otherchanges

Thereareanumberofotherchangesandadditions.Herearesomeoftheimportantones.

Youcannowusehighqualityiconsforyourgames.Constantscannowbedefinedintheirownform(ratherthanthroughtheGlobalGameSettings).Asaresulttheycanremainvisiblewhileyouaree.g.writingscripts.Youcanalsoloadandsavetheconstantstotextfiles.AlsoincludedfilesarenolongershownintheGlobalGameSettingsbutintheirownform.ManysmallvisualimprovementsAddedfunctionrandom_range(x1,x2),irandom(x),andirandom_range(x1,x2).Thelatterdogiveintegerresultsandcanincludexorx2.

Page 8: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Addedfunctionsmouse_wheel_upandmouse_wheel_down.Addedafunctionset_application_title(title)tosetthetitleoftheapplication(whichisshowninthetaskbar).Addedfunctionfile_text_eoln().Addedread-onlyvariabedebug_mode.Thereisnowagamesettingtodisallowscreensaversorpowersavingoptions(sleep,hybernate)whilethegameisrunning(defaultdisallowed).Addedfunctionsdisk_size(drive)anddisk_free(drive)andavariablegamemaker_version.RuntimeerrormessagesbetterindicatethepositionoftheerrorYoucannowchangetolocationofthetemporaryfiles,seethepageonPreferences....

Correctedbugs

Thefollowingbugswerecorrected.Anumberofothersmallerbugswerecorrectedaswell.

AnerrormessagewhenstartingtheMakeronVistawithActiveUserControlisnowremoved.CorrectedabugthatwhenusingAltmanyfieldsinformsbecameinvisibleunderVista.Correctedabugwithactionhintsnotshowingintheobjectandtimelineforms.Whenopeningagameorstartinganewone,nolongerforallopenchangedresourcewindowsaseparatesaveconfirmationquestionisasked.Correcteda(sortof)errorwiththeprecisionofcomparisonoperatorsincode.SolvedbugwithabadbackgroundfortheAppliesTofieldincodeeditor.Creatingastandalonenowcorrectlycheckswhetherthereareanyrooms.ReplacedallCtrl+AltcombinatationsbyShift+Ctrlbecausesomeof

Page 9: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

combinationsareimportantforGermankeyboards.Alsocorrectedtheshortcutforcreatingsprites.Insimplemodes,short-cutsforhiddenresourcesandmenuitemsnowaredisabledaswell.AlsotheScriptsmenuishidden.Correctedabuginthefunctionwindow_get_color().Increasedthelimitonthenumberofverticesindrawing3Dprimitivesformodelsfrom1000to32000.Correctedabuginignoringz-valueformodelvertices.CorrectedtheOutsideViewandBoundaryViewevents.Gamewillnowrun(withwarning)whenthereisnoenabledsoundcard.Whenthegamewindowloosesfocus,ioeventslikekeypressesarenowcleared.Correctedandimprovederrorreportingforthecreationcodeofroomsandinstancesinrooms.room_tile_addandroom_tile_add_extnowcorrectlysettheblendingcolortowhiteandreturnthecorrecttileindex.Nowcorrectlysettingtheapplicationtitletothefilename.Correctedabugindraw_line_width_colorwhenthelengthis0.Tileswithnegativescalefactorsarenowcorrectlydrawn.Changedthereadingandwritingofrealsintextfiles.Asdecimalseparatornowalwaysadotisused.However,whenreading,bothadotorcommaareaccepted.Agroupofresourcesthatisemptywillnowhavethecorrectclosedfoldericon.Solvedtheproblemwiththeflashingoftheresourcetree.Functionsstringandstring_formatnolongercrashwhenthenumberistoolargeandtheywillreturnthestringERROR.Longpathsarenowcorrectlydrawnwithdraw_path.Collapsingtheresourcetreenowworkscorrectly.Inanifcondition,avalueof0.5isnowtreatedastrue.Solvedabugthatsometimesoccuredwhenpressingthe~key.sign()functionnowcorrectlyreturns0whentheargumentis0.Inthepatheditor,whenchoosingaroom,clickingoutsidethemenunolongerclearstheroom.Slightlyenlargedthedebugformtoshowalltoolbaricons.Alsomadethewatchgridcolumnsscalewhentheformresizes.

Page 10: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Correctedabugthatcancauseacrashwhenresizingthegamewindowto0height.Solvedabuginds_grid_add/multiply/set_grid_region.Callstoscriptsandextensionfunctionsnowreturnavalueof0whentheydonotassignareturnvaluethemselves.Solvedaseriousbuginwhichcollisioneventswhereexecutedtwiceiftwoobjectshavecollisioneventswitheachother.Solvedabugindraw_text_extwithemptylines(multiple#)andaproblemwithdrawingstringsthatcontainsCR-LFpairs(whenusingmultilinestringsincode).Read-onlyfilescannowbeusedasincludedfileswithouterrors....

Page 11: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

UsingGameMaker

GameMakerisaneasytouseprogramforcreatingyourowncomputergames.Thissectionofthehelpfilegivesyoualltheinformationyouneedforcreatingyourfirstgames.Latersectionswilldiscussmoreadvancedtopics,howtopolishanddistributeyourgame,andthebuilt-inprogramminglanguageGMLthatconsiderablyextendsthepossibilities.

InformationonthebasicuseofGameMakercanbefoundinthefollowingpages:

IntroductionInstallationUpgradingtotheProEditionGettingStartedTheGlobalUserInterfaceDefiningSpritesSoundsandMusicBackgroundsDefiningObjectsEventsActionsCreatingRoomsDistributingyourGame

Page 12: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Soyouwanttocreateyourowncomputergames

Playingcomputergamesisfun.Butitisactuallymorefuntodesignyourowncomputergamesandletotherpeopleplaythem.Inthepast,creatingcomputergameswasnoteasy.Commercialcomputergamesyoubuynowadaystypicallytakeoneortwoyearsofdevelopmentwithteamsofanywherebetween10and50people.Budgetseasilyreachmillionsofdollars.Andallthesepeoplearehighlyexperienced:programmers,artdesigners,soundtechnicians,etc.

ButGameMakerhaschangedthis.WithGameMakeryoucancreateyourowncomputergamesquicklywithouttheneedtolearnaprogramminglanguage.OfcourseyoushouldnotexpecttocreateyourownHalo4orVirtuaTenniswithinafewweeks.Butthatisalsonotnecessary.Thejoyofplayingagameisnotrelatedtoitscomplexity.Simplergames,likeTetris,Bejeweled,SpaceInvaders,etc.arealotoffuntoplayandaloteasiertocreate.

GameMakeroffersanintuitiveandeasytousedrag-and-dropinterfacethatallowsyoutocreateyourowngamesveryquickly.Youcanimportandcreateimages,sprites(animatedimages)andsoundsandusethem.GameMakerisbundledwithaconsiderablecollectionofsuchresourcestogetyoustarted.Youcaneasilydefinetheobjectsinyourgameandindicatetheirbehavior,andyoucandefineappealingrooms(levels)inwhichthegametakesplace.Andifyouwantfullcontrolthereisactuallyaneasy-to-useprogramminglanguagebuiltintoGameMakerthatgivesyoufullcontroloverwhatishappeninginyourgame.

GameMakerfocusesontwo-dimensionalgames.Soitisnotmeanttocreate3DworldslikeQuake,eventhoughthereissomelimitedfunctionalityfor3Dgraphics.Butdon’tletthisputyoudown.Manygreatgamesusetwo-dimensionalspritetechnology,eventhoughtheylookvery3-dimensional.Anddesigningtwo-dimensionalgamesisaloteasier

Page 13: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

andfaster.

GameMakercomesintwoeditions,theLiteEditionandtheProEdition.TheLiteEditioncanbeusedfreeofchargebutitislimitedinitsfunctionalityandwilldisplaypopupmessages.Youcanthoughfreelydistributethegamesyoucreatewithit;youcanevensellthemifyoulike.Seetheenclosedlicenseagreementformoredetails.YouarestronglyencouragedtoupgradeyourcopyofGameMakertotheProEdition.ItwillconsiderablyextendthefunctionalityofGameMakeranditwillremovethelogowhenrunninggames.ThiswillalsosupportthefurtherdevelopmentofGameMaker.FormoreinformationonupgradingseetheProEditionpage.

ThishelpfilewilltellyouthemostimportantthingsyouneedtoknowaboutGameMakerandhowyoucancreateyourowngameswithit.Pleaserealizethat,evenwithaprogramlikeGameMaker,designingcomputergamesisnotcompletelyeffortless.Therearetoomanyaspectsthatareimportant:gameplay,graphics,sounds,userinteraction,etc.Startwitheasyexamplesandyouwillrealizethatcreatinggamesisgreatfun.Alsocheckthewebsite

http://www.yoyogames.com/

forlotsofexamples,tutorials,ideas,andlinkstoothersitesandforums.Andsoonyouwillbecomeamastergamemakeryourself.Enjoy.

Page 14: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Installation

Youprobablyalreadydidthisbutifnot,hereishowtoinstallGameMaker.Simplyruntheprogramgmaker80.exe.Followtheon-screeninstructions.Youcaninstalltheprogramanywhereyoulikebutitisbesttofollowthedefaultsuggestionsgiven.Onceinstallationiscompleted,intheStartmenuyouwillfindanewprogramgroupwhereyoucanstartGameMakerandreadthehelpfile.

GameMakeralsoinstallsaconsiderablenumberofimages,sprites(animatedimages)andsoundeffectsonyourcomputer,whichcanbeusedfreeofchargeinyourgames.Alsosomeexamplegamesareinstalled.AllthesecanbefoundinfolderswithinthelocationwhereyouinstalledGameMaker.

ThefirsttimeyourunGameMakeryouareaskedwhetheryouwanttoruntheprograminSimpleorAdvancedmode.Ifyouhavenotusedagamecreationprogrambeforeandyouarenotanexperiencedprogrammer,youhadbetterusesimplemode(soselectNo).Insimplemodefeweroptionsareshown.YoucaneasilyswitchtoadvancedmodelaterusingtheappropriateitemintheFilemenu.

Youwillalsobeshownatutorialattherightofthewindow.Thetutorialwillteachyouhowtoquicklycreateyourfirstgame.ItwillguideyouthroughthebasicstepsinusingGameMaker.IfyouhavenotusedGameMakerbeforeyouarestronglyadvisedtoworkyourwaythroughthetutorial.YoucanalwaystrythetutoriallaterthroughtheHelpmenu.

Requirements

AnycomputerthatislessthanfiveyearsoldshouldbeabletorunGameMakerwithoutanyproblems.

Tobemoreprecise,GameMakerrequiresaresonablymodernPCrunningWindows2000,XP,Vista,7,orlater.ADirectX8(orlater)

Page 15: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

compatiblegraphicscardwithatleast32MBofmemoryisrequiredformostcreatedgames.Itrequiresascreenresolutionofatleast800x600and65000(16-bit)colors(preferablyfullcolor).AlsoaDirectX8compatiblesoundcardisrequired.Makesureyouhavethemostrecentdriversinstalled.GameMakerrequiresDirectXversion8.0orlatertobeinstalledonyourcomputer.(YoucandownloadthenewestversionofDirectXfromtheMicrosoftwebsiteat:http://www.microsoft.com/windows/directx/.)Whendesigningandtestinggames,thememoryrequirementsareprettyhigh(atleast128MBandpreferablymore,alsodependingontheoperatingsystem).Whenjustrunninggames,thememoryrequirementsarelesssevereanddependalotonthetypeofgame.

Page 16: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

UpgradingtotheProEdition

GameMakercomesintwoeditions,theLiteEditionandtheProEdition.

TheLiteEditionismeantforthosethattaketheirfirststepsonthepathofdevelopinggames.Itcanbeusedforfreebutislimitedinitsfunctionality.Alsoitshowsapopuplogowhenrunninggamesandwillregularlyremindyouofupgradingtheprogram.WhenyouareusingGameMakerregularlyyouarestronglyrecommendedtoupgradeittotheProEdition.

TheProEditioncontainsconsiderablymorefunctionalityanddoesnotdisplayanylogosorpopupmessages.Moreprecisely,theProEditionhasthefollowingadditionalfunctionality:

NoGameMakerlogoisshownwhenrunningagame.Noregularpopupsremindyouofupgrading.Youcanuserotated,colorblendedandtranslucentsprites.Thereareadditionaloptionsinthespriteandimageeditors.Thereareadditionalactionsfore.g.CDmusic,rotatedtext,andcolorizedshapes.Youcanusespecialsoundeffectsandpositionalsound.Youcancreatesplashscreenswithmovies,images,webpages,texts,etc.Thereisaparticlesystemtocreateexplosions,fireworks,flames,rain,andothereffects.Anumberofadvanceddrawingfunctionsareavailable,forexamplecolorizedtextandtexturedpolygons.Itispossibletocreate3Dgamesusingfunctionsfor3Dgraphics.Itispossibletocreatemultiplayergamesthatcanbeplayedoveranetwork.Youcandefineyourownroomtransitions.Youcanusefunctionstocreate,load,andmodifyresources(sprites,backgrounds,etc.)whilethegameisrunning.Thereisacollectionoffunctionstocreateandusedatastructures.

Page 17: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Therearefunctionsformotionplanning.Yougetthepossibilitytoincludeadditionalfilesinthegameexecutablesthatcanbeusedwhenthegameisrun.TheProEditioncaneasilybeextendedusingextensionpackage.Thesecanbemadebyeverybodyandwillingeneralbeprovidedfreeofcharge.Threesuchextensionpackagesareincludedaddingmanyroomtransitions,windowsdialogs,andprintingfacilities.Youcandefineyourowntriggerevents.Youcanexportandimportresources,whichmakesiteasiertocollaborateongames.

UpgradingtheLiteEditiontotheProEditioncostsonly20EuroorUS$25(subjecttochange).Thisisaone-timefeethatwillatleastbevalidforallversions8.xofGameMaker.

WhenyouarerunningtheLiteEdition,wheneveryoustartGameMakerthefollowingformwillbeshown:

YoucanusethisformtoupgradetotheProEdition.Thereareanumberofwaystodothis.

Page 18: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Theeasiestwayistopurchasetheupgradeonline.TothisendpressthebuttonPurchaseProEditionOnline.YouwillbebroughttoawebpagewhereyoucanmakeyoupaymenteitherbycreditcardorthroughPayPal.ThepaymentwillbehandledbythecompanySoftWrapthatisourauthorizedpaymentprocessor.OnceyoumadethepaymentthesoftwarewillimmediatelybeupgradedtotheProEditionwithoutanyfurtheractionfromyourside.Carefullysave(andprint)theconfirmationyoureceiveasitcontainsyourpurchasereferencethatyoumightneedlaterifyouwanttoreinstallthesoftware.(Whenyouarerunningtheprogram,youcanalsoupgradeonlinebychoosingUpgradetoProEditionintheHelpmenu.)

IfyoupurchasedGameMakerbefore(andhence,haveanactivationcodeorapreviouspurchasereference)pressthebuttonEnterActivationCode.Youwillbebroughttoawebpagewhereyoucaneitherenteryouractivationcodeoryourpurchasereferencefromyourpreviouspayment.Hereyoucanalsoretrieveyourlicenseifyoulostit.AfteryoufilledinthecorrectinformationGameMakerwillbeupgradedtotheProEdition.NotethatyoumusthaveanInternetconnectionforactivation.(Whenyouarerunningtheprogram,youcanalsoupgradeonlinebychoosingEnterActivationCodeintheHelpmenu.)

Ifyoudon'twanttoupgradetotheProEditionatthisstage,pressthebuttonContinueUsingtheLiteEdition.

Page 19: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Gettingstarted

Creatingyourfirstgameisalwaysachallenge.Butifyouarewillingtoputalittlebitofeffortinit,itwillactuallyberathereasy.Youcanhaveitrunningwithinanhour.

EventhoughitisreallyeasytomakegameswithGameMakeryouwillneedtounderstandsomeofthebasicconcepts.TothisendyouarestronglyrecommendedtofollowthetutorialthatisshownwhenGameMakerisstarted.Ifyoudidremovethetutorialfromview,youcanalwaysmakeitvisibleagainbychoosingTutorialintheHelpmenu.

TheGlobalidea

BeforedelvingintothepossibilitiesofGameMakeritisgoodtogetafeelingfortheglobalideabehindtheprogram.GamescreatedwithGameMakertakeplaceinoneormorerooms.(Roomsareflat,not3D,buttheycancontain3D-lookinggraphics.)Intheseroomsyouplaceobjects,whichyoucandefineintheprogram.Typicalobjectsarethewalls,movingballs,themaincharacter,monsters,etc.Someobjects,likewalls,justsitthereanddon’tdoanything.Otherobjects,likethemaincharacter,willmovearoundandreacttoinputfromtheplayer(keyboard,mouse,andjoystick)andtoeachother.Forexample,whenthemaincharactermeetsamonsterhemightdie.ObjectsarethemostimportantingredientsofgamesmadewithGameMaker,soletustalkabitmoreaboutthem.

Firstofall,mostobjectsneedsomeimagetomakethemvisibleonthescreen.Suchimagesarecalledsprites.Aspriteisoftennotasingleimagebutasetofimagesthatareshownoneaftertheothertocreateananimation.Inthiswayitlookslikethecharacterwalks,aballrotates,aspaceshipexplodes,etc.Duringthegame,thespriteforaparticularobjectcanchange.(Sothecharactercanlookdifferentwhenitwalkstotheleftortotheright.)YoucancreateyouownspritesinGameMakeror

Page 20: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

loadthemfromfiles(e.g.PNGfilesoranimatedGIF’s).ManyspritescomebundledwithGameMakerthatyoucanusefreeofchargeinyourgames.

Certainthingswillhappentoobjects.Suchhappeningsarecalledevents.Objectscantakecertainactionswheneventshappen.Therearealargenumberofdifferenteventsthatcantakeplaceandalargenumberofdifferentactionsthatyoucanletyourobjectstake.Forexample,thereisacreationeventwhentheobjectgetscreated.(Tobemoreprecise,whenaninstanceofanobjectgetscreated;therecanbemultipleinstancesofthesameobject.)Forexample,whenaballobjectgetscreatedyoucangiveitsomemotionactionsothatitstartsmoving.Whentwoobjectsmeet,yougetacollisionevent.Insuchacaseyoucanmaketheballstoporreversedirection.Youcanalsoplayasoundeffect.TothisendGameMakerletsyoudefinesounds.Whentheplayerpressesakeyonthekeyboardthereisakeyboardevent,andtheobjectcantakeanappropriateaction,likemovinginthedirectionindicated.Wehopeyougettheidea.Foreachobjectyoudesign,youcanindicateactionsforvariousevents;inthiswaydefiningthebehavioroftheobject.

Onceyouhavedefinedyourobjectsitistimetodefinetheroomsinwhichtheywilllive.Roomscanbeusedforlevelsinyourgameortocheckoutdifferentplaces.Thereareactionstomovefromoneroomtoanother.Rooms,firstofall,haveabackground.Thiscanbeasimplecolororanimage.SuchbackgroundimagescanbecreatedinGameMakeroryoucanloadthemfromfiles.(Thebackgroundcandoalotofthingsbutforthetimebeing,justconsideritassomethingthatmakestheroomslooknice.)Next,youcanplacetheobjectsintheroom.Youcanplacemultipleinstancesofthesameobjectinaroom.So,forexample,youneedtodefinejustonewallobjectandcanuseitatmanyplaces.Alsoyoucanhavemultipleinstancesofthesamemonsterobjects,aslongastheyhavethesamebehavior.

Nowyouarereadytorunthegame.Thefirstroomwillbeshownandobjectswillcometolifebecauseoftheactionsintheircreationevents.Theywillstartreactingtoeachotherduetoactionsincollisioneventsandtheycanreacttotheplayerusingtheactionsinkeyboardormouseevents.

Page 21: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Soinsummary,thefollowingthings(oftencalledresources)playacrucialrole:

objects:whicharethetrueentitiesinthegamerooms:theplaces(levels)inwhichtheobjectslivesprites:(animated)imagesthatareusedtorepresenttheobjectssounds:thesecanbeusedingames,eitherasbackgroundmusicoraseffectsbackgrounds:theimagesusedasbackgroundfortherooms

Thereareactuallyanumberofothertypesofresources:paths,scripts,fonts,andtimelines.Theseareonlyimportantformorecomplicatedgames.YouwillonlyseethemwhenyourunGameMakerinadvancedmode.Theywillbetreatedintheadvancedchapterslaterinthisdocument.

Page 22: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Theglobaluserinterface

WhenyoustartGameMakerthefollowingformisshown.NotethattheformmightinrealityalsoshowsomeGameMakernewsandthetutorialmightbevisibleattherightside.

(Actually,thisiswhatyouseewhenyourunGameMakerinsimplemode.Inadvancedmodeanumberofadditionalitemsareshown.)Attheleft,youseethedifferentresourcesmentionedabove:Sprites,Sounds,Backgrounds,Objects,Roomsandtwomore:GameInformationandGlobalGameSettings.Atthetopthereisthefamiliarmenuandtoolbar.Inthischapterwewilldescribebrieflythevariousmenuitems,buttons,etc.Inthelaterchapterswediscussanumberofthemindetail.Notethatmanythingscanbeachievedindifferentways:bychoosingacommandfromthemenu,byclickingabutton,orbyrightclickingonaresource.

Filemenu

Inthefilemenuyoucanfindsomeoftheusualcommandstoloadandsavefiles,plusafewspecialones:

Page 23: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

New.Choosethiscommandtostartcreatinganewgame.Ifthecurrentgamewaschangedyouareaskedwhetheryouwanttosaveit.Thereisalsoatoolbarbuttonforthis.Open.Opensagamefile.GameMakerfileshavetheextension.gmk.Youcanalsoopenold.gm6files.(Ifyouwanttoopen.gmdfilescreatedwithversion5ofGameMakeryoumustselecttheappropriatefiletypeatthebottomofthedialog.Thesemightthoughnotworkcorrectlyinthenewversion.)Thereisatoolbarbuttonforthiscommand.YoucanalsoopenagamebydraggingthefileintotheGameMakerwindow.RecentFiles.Usethissubmenutoreopengamefilesyourecentlyopened.Save.Savesthegamedesignfileunderitscurrentname.Ifnonamewasspecifiedbefore,youareaskedforanewname.Youcanonlyusethiscommandwhenthefilewaschanged.Again,thereisatoolbarbuttonforthis.SaveAs.Savesthegamedesignfileunderadifferentname.Youareaskedforanewname.CreateExecutable.Onceyourgameisreadyyouwillprobablywanttogiveittootherstoplay.Usingthiscommandyoucancreateastand-aloneversionofyourgame.Thisissimplyanexecutablethatyoucangivetootherpeopletorun.AdvancedMode.WhenclickingonthiscommandGameMakerwillswitchbetweensimpleandadvancedmode.Inadvancedmodeadditionalcommandsandresourcesareavailable.Exit.Probablyobvious.PressthistoexitGameMaker.Ifyouchangedthecurrentgameyouwillbeaskedwhetheryouwanttosaveit.

Editmenu

Theeditmenucontainsanumberofcommandsthatrelatetothecurrentlyselectedresource(object,sprite,sound,etc.).Dependingonthetypeofresourcesomeofthecommandsmaynotbevisible.

Insertresource.Insertsanewinstanceofthecurrentlyselected

Page 24: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

typeofresourcebeforethecurrentone.Aformwillopeninwhichyoucanchangethepropertiesoftheresource.Thiswillbetreatedindetailinthefollowingchapters.Duplicate.Makesacopyofthecurrentresourceandaddsit.Aformisopenedinwhichyoucanchangetheresource.Delete.Deletesthecurrentlyselectedresource(orgroupofresources).Becareful.Thiscannotbeundone.Youwill,though,bewarned.Rename.Givestheresourceanewname.Thiscanalsobedoneinthepropertyformfortheresource.Also,youcanselecttheresourceandthenclickonthename.Properties.Usethiscommandtobringuptheformtoedittheproperties.Notethatallthepropertyformsappearwithinthemainform.Youcaneditmanyofthematthesametime.Youcanalsoeditthepropertiesbydoubleclickingontheresource.

Notethatallthesecommandscanalsobegiveninadifferentway.Right-clickonaresourceorresourcegroup,andtheappropriatepop-upmenuwillappear.

Resourcesmenu

Inthismenu,youcancreatenewresourcesofeachofthedifferenttypes.Notethatforeachofthemthereisalsoabuttononthetoolbarandakeyboardshortcut.Alsoyoucanchangethegameinformationandtheglobalgamesettings.

Runmenu

Thismenuisusedtorunthegame.Therearetwowaystorunagame.

Runnormally.Runsthegameasitwouldnormallyrun.Thegameisruninthemostefficientwayandwilllookandactasinanexecutablegame.RuninDebugmode.Runsthegameindebugmode.Inthismode

Page 25: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

youcancheckcertainaspectsofthegameandyoucanpauseandstepthroughit.Thisisusefulwhensomethinggoeswrongbutisabitadvanced.

Onceyourgameisfinished,youcancreateastand-aloneexecutableofthegameusingthecommandinthefilemenu.

Windowmenu

Inthismenuyoufindsomeoftheusualcommandstomanagethedifferentpropertywindowsinthemainform:

Cascade.Cascadeallthewindowssuchthateachofthemispartiallyvisible.ArrangeIcons.Arrangealltheiconifiedpropertywindows.(Usefulinparticularwhenresizingthemainform.)CloseAll.Closeallthepropertywindows,askingtheuserwhetherornottosavethechangesmade.

Helpmenu

Hereyoufindsomecommandstohelpyou:

Contents.Usethiscommandtoshowthishelpfile.Tutorials.UsethissubmenutoshowthedifferenttutorialsthatareprovidedwithGameMakertoteachyouhowtomakeyourfirstgames.UpgradetoProEdition.YoucanusethiscommandtoupgradetheLiteEditionofGameMakertotheProEditionOnline.TheProEditionhasmanyaditionalfeatures.EnterActivationCode.IfyoupurchasedGameMakerbefore(andhence,haveanactivationcodeorapreviouspurchasereference)youcanusethiscommandtoenteryourcode.Youwillbebroughttoawebpagewhereyoucaneitherenteryouractivationcodeoryourpurchasereferencefromyourpreviouspayment.News.HereyoucanseethemostrecentnewsaboutGameMaker.

Page 26: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Book.ThiscommandwillbringyoutoalocationonthewebsitewhereyoucanfindinformationabouttheGameMakerbook.MoreTutorials.Thiscommandwillbringyoutoalocationonthewebsitewhereyoucandownloadsomemoretutorials.Website.ConnectsyoutotheGameMakerwebsitewhereyoucanfindinformationaboutthemostrecentversionofGameMakerandcollectionsofgamesandresourcesforGameMaker.Forum.ThiscommandwillbringyoutotheforumwhereusershelpeachotherwithmanyaspectsofGameMaker.Wiki.ThiscommandwillbringyoutotheGameMakerwikiwhereyoucanfindplentyofinformationabouttheuseofGameMaker.AboutGameMaker.GivessomeshortinformationaboutthisversionofGameMaker.

Theresourceexplorer

Attheleftofthemainformyoufindtheresourceexplorer.Hereyouwillseeatree-likeviewofallresourcesinyourgame.ItworksinthesamewayastheWindowsExplorer,andyouaremostlikelyfamiliarwithit.Ifanitemhasa+signinfrontofityoucanclickonthesigntoseetheresourcesinsideit.Byclickingonthe-signthesedisappearagain.Youcanchangethenameofaresource(exceptthetoplevelones)byselectingit(withasingleclick)andthenclickingonthename.Doubleclickonaresourcetoedititsproperties.UsetherightmousebuttontoaccessthesamecommandsasintheEditmenu.

Youcanchangetheorderoftheresourcesbyclickingonthemwiththemouseandholdingthemousebuttonpressed.Nowyoucandragtheresourcetotheappropriateplace.(Ofcoursetheplacemustbecorrect.Youcannotdragasoundintothelistofsprites.)

Page 27: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Definingsprites

Spritesarethevisualrepresentationsofalltheobjectsinthegame.Aspriteiseitherasingleimage,drawnwithanydrawingprogramyoulike,orasetofimagesthat,whenplayedoneafteranother,lookslikeananimatedmotion.Forexample,thefollowingfourimagesformaspriteforacharactermovingtotheright.

Whenyoumakeagameyounormallystartbycollectingasetofnicespritesfortheobjectsinyourgame.AconsiderablenumberofusefulspritesisbundledwithGameMaker.OthercollectionsofinterestingspritescanbefoundontheGameMakerwebsite.Manymorespritescanbefoundontheweb,normallyintheformofpngoranimatedgiffiles.

Tocreateasprite,choosetheitemCreateSpritefromtheResourcesmenu,orusethecorrespondingbuttononthetoolbar.Thefollowingformwillpopup.

Atthetop-leftyoucanindicatethenameofthesprite.Allsprites(andallotherresources)haveaname.It'sbesttogiveeachspriteadescriptivename.Makesureallresourcesgetdifferentnames.Eventhoughthisis

Page 28: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

notstrictlyrequired,youarestronglyadvisedtouseonlylettersanddigitsandtheunderscoresymbol(_)inanameofasprite(andanyotherresource)andtoletitstartwithaletter.Inparticulardon'tusethespacecharacter.Thiswillbecomeimportantonceyoustartusingcode.

Toloadasprite,clickonthebuttonLoadSprite.Aspecialfiledialogopensinwhichyoucanchoosethesprite:

Theleftpartlookslikethestandardfileselectorinwhichyoucanselectthespritethatyouwant.Attherightyougetapreviewoftheanimatedspriteandsomeinformationaboutit.Hereyoucanalsoindicatethatyouwanttomakethespriteopaque(thatis,removeanytransparentparts),whethertoremovethebackground,makingittransparent(default),andwhethertosmooththeedgesofthesprite,whichcanimproveitsappearance.WhenyouarehappywiththeresultpressOpentoloadthesprite.

GameMakercanloadmanydifferentgraphicsfiles.Whenyouloadananimatedgif,thedifferentsubimagesformthespriteimages.Whenthefilenameendswith_stripXX,withXXanumber,itisconsideredtocontainastripofXXsubimagesnexttoeachother(notforgiffiles).Forexample,aimagefilewithnameball_strip4.pngisassumedtocontain4subimages.

Oncethespriteisloadedthefirstsubimageisshownontheright.When

Page 29: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

therearemultiplesub-images,youcancyclethroughthemusingthearrowbuttons.

WiththebuttonEditSpriteyoucaneditthesprite,orevencreateacompletelynewsprite.GameMakerhasanextensivebuilt-inspriteandimageeditor.FormoreinformationseethesectionsonEditingyourspritesandonEditingindividualsubimages.

Page 30: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Soundsandmusic

Mostgameshavecertainsoundeffectsandsomebackgroundmusic.ManyusefulsoundeffectscanbefoundontheGameMakerwebsite.Manymorecanbefoundonotherplacesontheweb.

Tocreateasoundresourceinyourgame,usetheitemCreateSoundintheResourcesmenuorusethecorrespondingbuttononthetoolbar.Thefollowingformwillpopup.

Toloadasound,pressthebuttonlabeledLoadSound.Afileselectordialogpopsupinwhichyoucanselectthesoundfile.Therearetwotypesofsoundfiles,wavefilesandmidifiles.Wavefilesareusedforshortsoundeffects.Theyusealotofmemorybutplayinstantaneously.Usetheseforallthesoundeffectsinyourgame.Midifilesdescribemusicinadifferentway.Asaresulttheyusealotlessmemory,buttheyarelimitedtoinstrumentalbackgroundmusic.Also,defaultonlyonemidisoundcanplayatanytime.

Onceyouloadamusicfileyoucanlistentothesoundusingtheplaybutton.ThereisalsoabuttonSaveSoundtosavethecurrentsoundtoafile.Thisbuttonisnotreallyrequiredbutyoumightneeditifyoulosttheoriginalsound.

Page 31: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Backgrounds

Thethirdtypeofbasicresourceisbackgrounds.Backgroundsareusuallylargeimagesthatareusedasbackgrounds(orforegrounds)fortheroomsinwhichthegametakesplace.Oftenbackgroundimagesaremadeinsuchawaythattheycantileanareawithoutvisualcracks.Inthiswayyoucanfillthebackgroundwithsomepattern.AnumberofsuchusefulbackgroundsarebundledwithGameMaker.OtherscanbefoundontheGameMakerwebsite.Manymorecanbefoundatotherplacesontheweb.

Tocreateabackgroundresourceinyourgame,usetheitemCreateBackgroundintheResourcesmenuorusethecorrespondingbuttononthetoolbar.Thefollowingformwillpopup.

Atthetop-leftyoucanindicatethenameofthebackground.Youarestronglyrecommendedtogiveeverybackground(andotherresource)adescriptivename.

PressthebuttonLoadBackgroundtoloadabackgroundimage.Afileselectorisshowninwhichyoucanselectthebackgroundyouwant.Attherightofthedialogyoucanindicatewhetheryouwanttomakethebackgroundopaque(thatis,removeanytransparentparts),whethertoremovethebackground,makingittransparent(defaultnot),andwhethertosmooththeedgesofthebackground,whichcanimproveitsappearancewhenitispartiallytransparent.Whenyouarehappywiththe

Page 32: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

resultpressOpentoloadthebackground.GameMakersupportsmanyimageformats.Backgroundimagescannotbeanimated!

YoucanchangethebackgroundorcreateanewoneusingthebuttonEditBackground.Thiswillopenanextensiveimageeditor.ForinformationonhowtousetheimageeditorseethesectiononEditingimages.

Becarefulwithlargebackgrounds.Someoldgraphicscardscannothandleimagesthatarelargerthanthescreen.Sopreferablykeepyourbackgroundimagessmallerthan1024x1024.

Page 33: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Definingobjects

Withtheresourcesyouhaveseensofaryoucanaddsomeniceimagesandsoundstothegame,buttheydon'tdoanything.WenowcometothemostimportantresourceofGameMaker,theobjects.Objectsareentitiesinthegamethatdothings.Mostofthetimetheyhaveaspriteasagraphicalrepresentationsothatyouseethem.Theyhavebehaviorbecausetheycanreacttocertainevents.Allthingsyouseeinthegame(exceptforthebackground)areobjects.(Ortobemoreprecise,theyareinstancesofobjects.)Thecharacters,themonsters,theballs,thewalls,etc.areallobjects.Theremightalsobecertainobjectsthatyoudon'tseebutwhichcontrolcertainaspectsofthegameplay.

Pleaserealizethedifferencebetweenspritesandobjects.Spritesarejust(animated)imagesthatdon'thaveanybehavior.Objectsnormallyhaveaspritetorepresentthembutobjectshavebehavior.Withoutobjectsthereisnogame!

Alsorealizethedifferencebetweenobjectsandinstances.Anobjectdescribesacertainentity,e.g.amonster.Therecanbemultipleinstancesofthisobjectinthegame.Whenwetalkaboutaninstancewemeanoneparticularinstanceoftheobject.Whenwetalkaboutanobjectwemeanalltheinstancesofthisobject.

Tocreateanobjectinyourgame,chooseCreateObjectfromtheResourcesmenu.Thefollowingformwillappear:

Page 34: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thisisrathercomplex.Attheleftthereissomegeneralinformationabouttheobject.Inthemiddlethereisthelistofeventsthatcanhappentotheobject.Attherighttherearethedifferentactionstheobjectcanperform.Eventsandactionswillbediscussedinthecomingchapters.

Asalways,youcan(andshould)giveyourobjectaname.Nextyoucanchoosethespritefortheobject.Tothisend,clickwiththeleftmousebuttononthespriteboxorthemenubuttonnexttoit.Amenuwillpop-upwithalltheavailablesprites.Selecttheoneyouwanttousefortheobject.Ifyoudonothaveaspriteyet,youcanclickthebuttonNewtocreateanewspriteresourceandchangeit.Also,whenyouselectaresourcetherewillbeabuttonEditherethatyoucanusetochangethesprite.Thisisfasterthanfirstfindingtheresourceinthelistofresourcesandthenindicatingyouwanttoeditit.

Belowthistherearetwocheckboxes.Visibleindicateswhetherinstancesofthisobjectarevisible.Clearly,mostobjectsarevisible,butsometimesitisusefultohaveinvisibleobjects.Forexample,youcanusethemforwaypointsforamovingmonster.Invisibleobjectswillreacttoeventsandotherinstancesdocollidewiththem.TheboxlabeledSolidindicateswhetherthisisasolidobject(likeawall).Collisionswithsolidobjectsaretreateddifferentlyfromcollisionswithnon-solidobjects.YouarestronglyadvisedtouseSolidonlyforobjectthatarenotmoving.

Page 35: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 36: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Events

GameMakeruseswhatiscalledaneventdrivenapproach.Thisworksasfollows.Wheneversomethinghappensinthegametheinstancesoftheobjectsgetevents(kindofmessagestellingthatsomethinghashappened).Theinstancescanthenreacttothesemessagesbyexecutingcertainactions.Foreachobjectyoumustindicatetowhicheventsitrespondsandwhatactionsitmustperformwhentheeventoccurs.Thismaysoundcomplicatedbutisactuallyveryeasy.Firstofall,formosteventstheobjectdoesnothavetodoanything.Fortheeventswheresomethingmustbedoneyoucanuseaverysimpledrag-and-dropapproachtoindicatetheactions.

Inthemiddleoftheobjectpropertyformthereisalistofeventstowhichtheobjectmustreact.Initiallyitisempty.YoucanaddeventstoitbypressingthebuttonlabeledAddEvent.Aformwillappearwithalldifferenttypesofevents.Hereyouselecttheeventyouwanttoadd.Sometimesamenupopsupwithextrachoices.Forexample,forthekeyboardeventyoumustselectthekey.Belowyoufindacompletelistofthedifferenteventsplusdescriptions.Oneeventinthelistwillbeselected.Thisistheeventwearecurrentlychanging.Youcanchangetheselectedeventbyclickingonit.Attherighttherearealltheactionsrepresentedbylittleicons.Theyaregroupedinanumberoftabbedpages.Inthenextchapteryouwillfinddescriptionsofalltheactionsandwhattheydo.Betweentheeventsandtheactionsthereistheactionlist.Thislistcontainstheactionsthatmustbeperformedforthecurrentevent.Toaddactionstothelist,dragthemwithyourmousefromtherighttothelist.Theywillbeplacedbeloweachother,withashortdescription.Foreachactionyouwillbeaskedtoprovideafewparameters.Thesewillalsobedescribedinthenextchapter.Soafteraddingafewactionsthesituationmightlookasfollows:

Page 37: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Nowyoucanstartaddingactionstoanotherevent.Clickonthecorrecteventwiththeleftmousebuttontoselectitanddragactionsinthelist.

Youcanchangetheorderoftheactionsinthelistagainusingdrag-and-drop.Ifyouholdthe<Alt>keywhiledragging,youmakeacopyoftheaction.Youcanevenusedrag-and-dropbetweenactionlistsfordifferentobjects.Whenyouclickwiththerightmousebuttononanaction,amenuappearsinwhichyoucandeletetheselectedaction(canalsobedonebyusingthe<Del>key)orcopyandpasteactions.(Youcanselectmultipleactionsforcutting,copying,ordeletingbyholdingthe<Shift>keyof<Ctrl>key.Press<Ctrl><A>toselectallactions.)Whenyouholdyourmouseatrestaboveanaction,alongerdescriptionisgivenoftheaction.Seethenextchapterformoreinformationonactions.

TodeletethecurrentlyselectedeventtogetherwithallitsactionspressthebuttonlabeledDelete.(Eventswithoutanyactionswillautomaticallybedeletedwhenyouclosetheformsothereisnoneedtodeletethemmanually.)Ifyouwanttoassigntheactionstoadifferentevent(forexample,becauseyoudecidedtouseadifferentkeyforthem)pressthebuttonlabeledChangeandpicktheneweventyouwant.(Theeventshouldnotbedefinedalready!)Usingthemenuthatpopsupwhenright-clickingontheeventlist,youcanalsoduplicateanevent,thatis,addaneweventwiththesameactions.

Asindicatedabove,toaddanevent,pressthebuttonAddEvent.Thefollowingformpopsup:

Page 38: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Hereyouselecttheeventyouwanttoadd.Sometimesamenupopsupwithextrachoices.Hereisadescriptionofthevariousevents.(Againrememberthatyounormallyuseonlyafewofthem.)

CreateeventThiseventhappenswhenaninstanceoftheobjectiscreated.Itisnormallyusedtosettheinstanceinmotionand/ortosetcertainvariablesfortheinstance.

DestroyeventThiseventhappenswhentheinstanceisdestroyed.Tobeprecise,ithappensjustbeforeitisdestroyed,sotheinstancedoesstillexistwhentheeventisexecuted!Mostofthetimethiseventisnotusedbutyoucanforexampleuseittochangethescoreortocreatesomeotherobject.

AlarmeventsEachinstancehas12alarmclocks.Youcansetthesealarmclocksusingcertainactions(seenextchapter).Thealarmclockthenticksdownuntilitreaches0atwhichmomentthealarmeventisgenerated.Toindicatetheactionsforagivenalarmclock,youfirstneedtoselectitinthemenu.Alarmclocksareveryuseful.Youcanusethemtoletcertainthingshappenfromtimetotime.Forexampleamonstercanchangeitsdirectionofmotionevery20steps.(Insuchcasesoneoftheactionsintheeventmustsetthealarmclockagain.)

StepeventsThestepeventhappenseverystepofthegame.Hereyoucanputactionsthatneedtobeexecutedcontinuously.Forexample,ifoneobjectshouldfollowanother,hereyoucanadaptthedirectionofmotiontowardstheobjectwearefollowing.Becarefulwiththiseventthough.Don'tput

Page 39: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

manycomplicatedactionsinthestepeventofobjectsofwhichtherearemanyinstances.Thismightslowthegamedown.Tobemoreprecise,therearethreedifferentstepevents.Normallyyouonlyneedthedefaultone.Butusingthemenuyoucanalsoselectthebeginstepeventandtheendstepevent.Thebeginstepeventisexecutedatthebeginningofeachstep,beforeanyothereventstakeplace.Thenormalstepeventisexecutedjustbeforetheinstancesareputintheirnewpositions.Theendstepeventisexecutedattheendofthestep,justbeforethedrawing.Thisistypicallyusedtochangethespritedependingonthecurrentdirection.

CollisioneventsWhenevertwoinstancescollide(thatis,theirspritesoverlap)acollisioneventappears.Well,tobeprecisetwocollisioneventoccur;oneforeachinstance.Theinstancecanreacttothiscollisionevent.Tothisend,fromthemenuselecttheobjectwithwhichyouwanttodefinethecollisionevent.Nextyouplacetheactionshere.

Thereisadifferenceinwhathappenswhentheinstancecollideswithasolidobjectoranon-solidobject.Firstofall,whentherearenoactionsinthecollisionevent,nothinghappens.Thecurrentinstancesimplykeepsonmoving;evenwhentheotherobjectissolid.Whenthecollisioneventcontainsactionsthefollowinghappens:

Whentheotherobjectissolid,theinstanceisplacedbackatitspreviousplace(beforethecollisionoccurs).Thentheeventisexecuted.Finally,theinstanceismovedtoitsnewposition.Soiftheevente.g.reversesthedirectionofmotion,theinstancebouncesagainstthewallwithoutstopping.Ifthereisstillacollision,theinstanceiskeptatitspreviousplace.Soiteffectivelystopsmoving.

Whentheotherobjectisnotsolid,theinstanceisnotputback.Theeventissimplyexecutedwiththeinstanceatitscurrentposition.Also,thereisnosecondcheckforacollision.Ifyouthinkaboutit,thisisthelogicalthingthatshouldhappen.Becausetheobjectisnotsolid,wecansimplymoveoverit.Theeventnotifiesusthatthisishappening.

Therearemanyusesforthecollisionevent.Instancescanuseitto

Page 40: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

bounceagainstwalls.Youcanuseittodestroyobjectswhen,forexample,theyarehitbyabullet.

KeyboardeventsWhentheplayerpressesakey,akeyboardeventhappensforallinstancesofallobjects.Thereisadifferenteventforeachkey.Inthemenuyoucanpickthekeyforwhichyouwanttodefinethekeyboardeventandnextdragactionsthere.Clearly,onlyafewobjectsneedeventsforonlyafewkeys.Yougetaneventineverystepaslongastheplayerkeepsthekeydepressed.Therearetwospecialkeyboardevents.Oneiscalled<Nokey>.Thiseventhappensineachstepwhennokeyispressed.Thesecondoneiscalled<Anykey>andhappenswhateverkeyispressed.Whentheplayerpressesmultiplekeys,theeventsforallthekeyspressedhappen.Notethatthekeysonthenumerickeypadonlyproducethecorrespondingeventswhen<NumLock>ispressed.

MouseeventsAmouseeventhappensforaninstancewheneverthemousecursorliesinsidethespriterepresentingtheinstance.Dependingonwhichmousebuttonsarepressedyougetthenobutton,leftbutton,rightbutton,ormiddlebuttonevent.Themousebuttoneventsaregeneratedineachstepaslongastheplayerkeepsthemousebuttonpressed.Thepresseventsareonlygeneratedoncewhenthebuttonispressed.Thereleaseeventsareonlygeneratedwhenthebuttonisreleased.Notethattheseeventsonlyoccurwhenthemouseisabovetheinstance.Ifyouwanttoreacttomousepressorreleaseeventsatanarbitraryplace,usetheglobalmouseeventsthatcanbefoundinasubmenu.Therearetwospecialmouseevents.Themouseentereventhappenswhenthemouseenterstheinstance.Themouseleaveeventhappenswhenthemouseleavestheinstance.Theseeventsaretypicallyusedtochangetheimageorplaysomesound.Mousewheelupandmousewheeldowneventshappenwhentheusermovesthemousewheel.Finallythereareanumberofeventsrelatedtothejoystick.Youcanindicateactionsforthefourmaindirectionsofthejoystick(inadiagonaldirectionbotheventshappen).Alsoyoucandefineactionsforupto8joystickbuttons.Youcandothisbothfortheprimaryjoystickandthesecondaryjoystick.

Otherevents

Page 41: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thereareanumberofothereventsthatcanbeusefulincertaingames.Theyarefoundinthismenu.Thefollowingeventscanbefoundhere:

Outsideroom:Thiseventhappenswhentheinstanceliescompletelyoutsidetheroom.Thisistypicallyagoodmomenttodestroyit.Intersectboundary:Thiseventhappenswhentheinstanceintersectstheboundaryoftheroom,thatis,itlies(atleast)partiallyoutsidetheroom.Views:Hereyoufindanumberofeventsthatareusefulwhenyouuseviewsinyourrooms.Theseeventstestwhethertheinstanceliescompletelyoutsideaparticularvieworinteresectstheviewboundary.Gamestart:Thiseventhappensforallinstancesinthefirstroomwhenthegamestarts.Ithappensbeforetheroomstartevent(seebelow)butafterthecreationeventsfortheinstancesintheroom.Thiseventistypicallydefinedinonlyone"controller"objectandisusedtostartsomebackgroundmusicandtoinitializesomevariables,orloadsomedata.Gameend:Theeventhappenstoallinstanceswhenthegameends.Againtypicallyjustoneobjectdefinesthisevent.Itisforexampleusedtostorecertaindatainafile.Roomstart:Thiseventhappensforallinstancesinitiallyinaroomwhentheroomstarts.Ithappensafterthecreationevents.Roomend:Thiseventhappenstoallexistinginstanceswhentheroomends.Nomorelives:GameMakerhasabuilt-inlivessystem.Thereisanactiontosetandchangethenumberoflives.Wheneverthenumberoflivesbecomeslessthanorequalto0,thiseventhappens.Itistypicallyusedtoendorrestartthegame.Nomorehealth:GameMakerhasabuilt-inhealthsystem.Thereisanactiontosetandchangethehealth.Wheneverthehealthbecomeslessthanorequalto0,thiseventhappens.Itistypicallyusedtoreducethenumberoflivesortorestartthegame.Animationend:Asindicatedabove,ananimationconsistsofanumberofimagesthatareshownoneaftertheother.Afterthelastoneisshownwestartagainwiththefirstone.Theeventhappensat

Page 42: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

preciselythatmoment.Asanexample,thiscanbeusedtochangetheanimation,ordestroytheinstance.Endofpath:Thiseventhappenswhentheinstancefollowsapathandtheendofthepathisreached.Closebutton:Thiseventhappenswhentheuserclicksontheclosebuttonofthewindow.ThisonlyhappenswhendisablinginthegamesettingstheoptiontohavetheclosebuttonbehaveastheEscapekey.Userdefined:Thereare16oftheseevents.Theynormallyneverhappenunlessyouyourselfcallthemfromapieceofcode.

DraweventInstances,whenvisible,drawtheirspriteineachsteponthescreen.Whenyouspecifyactionsinthedrawingevent,thespriteisnotdrawn,buttheseactionsareexecutedinstead.Thiscanbeusedtodrawsomethingotherthanthesprite,orfirstmakesomechangestospriteparameters.Thereareanumberofdrawingactionsthatareespeciallymeantforuseinthedrawingevent.Notethatthedrawingeventisonlyexecutedwhentheobjectisvisible.Alsonotethat,independentofwhatyoudraw,collisioneventsarebasedonthespritethatisassociatedwiththeinstance.

KeyPresseventsThiseventissimilartothekeyboardeventbutithappensonlyoncewhenthekeyispressed,ratherthancontinuously.Thisisusefulwhenyouwantanactiontohappenonlyonce.

KeyReleaseeventsThiseventissimilartothekeyboardeventbutithappensonlyoncewhenthekeyisreleased,ratherthancontinuously.

InsomesituationitisimportanttounderstandtheorderinwhichGameMakerprocessestheevents.Thisisasfollows:

BeginstepeventsAlarmeventsKeyboard,Keypress,andKeyreleaseeventsMouseevents

Page 43: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Normalstepevents(nowallinstancesaresettotheirnewpositions)CollisioneventsEndstepeventsDrawevents

Thecreate,destroy,andothereventsareperformedwhenthecorrespondingthingshappen.

Page 44: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Actions

ActionsindicatethethingsthathappeninagamecreatedwithGameMaker.Actionsareplacedineventsofobjects.Whenevertheeventtakesplacetheseactionsareperformed,resultingincertainbehaviorfortheinstancesoftheobject.Therearealargenumberofdifferentactionsavailableanditisimportantthatyouunderstandwhattheydo.Inthischapterwedescribetheactionsavailableinsimplemode.NotethatanumberoftheseactionsareonlyavailableintheProEditionofGameMaker.Thiswillbeindicated.

Alltheactionsarefoundinthetabbedpagesattherightoftheobjectpropertyform.Therearesixsetsofactions.Youselectthesetyouwantbyclickingonthecorrecttab.Whenyouholdyoumouseaboveoneoftheactions,ashortdescriptionisshowntoremindyouofitsfunction.

Letusbrieflyrepeat:Toputanactioninanevent,justdragitfromthetabbedpagestotheactionlist.Youcanchangetheorderinthelist,againusingdragging.Holdingthe<Alt>keywhiledraggingmakesacopyoftheaction.(Youcandragandcopyactionsbetweenthelistsindifferentobjectpropertyforms.)Usetherightmousebuttonandselectthecorrectmenuitemtoremoveactions(orusethe<Del>key)andtocopyandpasteselectedactions.

Whenyoudropanactionintheactionlist,awindowwillpop-upmostofthetime,inwhichyoucanfillincertainparametersfortheaction.Theparameterswillbedescribedbelowwhendescribingtheactions.Twotypesofparametersappearinmanyactionssowewilldescribethesehere.Atthetopyoucanindicatetowhichinstancetheactionapplies.Thedefaultisself,whichistheinstanceforwhichtheactionisperformed.Mostofthetime,thisiswhatyouwant.Inthecaseofacollisionevent,youcanalsospecifytoapplytheactiontotheotherinstanceinvolvedinthecollision.Forinstance,inthiswayyoucandestroytheotherinstance.Finally,youcanchoosetoapplytheactiontoallinstancesofaparticularobject.Inthiswayyoucouldchangeallred

Page 45: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ballsintoblueballs.ThesecondtypeofparameteristheboxlabeledRelative.Bycheckingthisbox,thevaluesyoutypeinarerelativetothecurrentvalues.Forexample,inthiswayyoucanaddsomethingtothecurrentscore,ratherthanchangingthecurrentscoretothenewvalue.Theotherparameterswillbedescribedbelow.Youcanlaterchangetheparametersbydoubleclickingontheaction.

Informationonthedifferentactionscanbefoundinthefollowingpages:

MoveActionsMainActions,Set1MainActions,Set2ControlActionsScoreActionsDrawActionsUsingVariablesandExpressions

Page 46: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moveactions

Thefirstsetofactionsconsistsofthoserelatedtomovementofobjects.Thefollowingactionsexist:

MoveFixedUsethisactiontostarttheinstancemovinginaparticulardirection.Youcanindicatethedirectionusingthebuttonswiththearrowsonit.Usethemiddlebuttontostopthemotion.Alsoyouneedtospecifythespeedofthemotion.Thisspeedisgiveninpixelsperstep.Preferablydon'tusenegativespeeds.Youcanspecifymultipledirections.Inthiscasearandomchoiceismade.Inthiswayyoucanletamonsterstartmovingeitherleftorright.

MoveFreeThisisthesecondwaytospecifyamotion.Hereyoucanindicateaprecisedirection.Thisisananglebetween0and360degrees.0meanstotheright.Thedirectioniscounter-clockwise.Soforexample90indicatesanupwarddirection.Ifyouwantanarbitrarydirection,youcantyperandom(360).Asyouwillseebelowthefunctionrandomgivesarandomnumbersmallerthantheindicatedvalue.AsyoumighthavenoticedthereisacheckboxlabeledRelative.Ifyoucheckthis,thenewmotionisaddedtothepreviousone.Forexample,iftheinstanceismovingupwardsandyouaddsomemotiontotheleft,thenewmotionwillbeupwardstotheleft.

MoveTowardsThisactiongivesathirdwaytospecifyamotion.Youindicateapositionandaspeedandtheinstancestartsmovingwiththespeedtowardstheposition.(Itwon'tstopattheposition!)Forexample,ifyouwantabullettoflytowardsthepositionofthespaceshipyoucanuseaspositionspaceship.x,spaceship.y.(Youwilllearnmoreabouttheuseofvariableslikethesebelow.)IfyouchecktheRelativebox,youspecifythepositionrelativetothecurrentpositionoftheinstance.(Thespeedisnottakenrelatively!)

Page 47: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

SpeedHorizontalThespeedofaninstanceconsistsofahorizontalpartandaverticalpart.Withthisactionyoucanchangethehorizontalspeed.Apositivehorizontalspeedmeansamotiontotheright.Anegativeonemeansamotiontotheleft.Theverticalspeedwillremainthesame.Userelativetoincreasethehorizontalspeed(ordecreaseitbyprovidinganegativenumber).

SpeedVerticalInasimilarway,withthisactionyoucanchangetheverticalspeedoftheinstance.

SetGravityWiththisactionyoucancreategravityforthisparticularobject.Youspecifyadirection(anglebetween0and360degrees)andaspeed,andineachstepthisamountofspeedinthegivendirectionisaddedtothecurrentmotionoftheobjectinstance.Normallyyouneedaverysmallspeedincrement(like0.01).Typicallyyouwantadownwarddirection(270degrees).IfyouchecktheRelativeboxyouincreasethegravityspeedanddirection.Notethat,contrarytoreallife,differentobjectcanhavedifferentgravitydirections.

ReverseHorizontalWiththisactionyoureversethehorizontalmotionoftheinstance.Thiscanforexamplebeusedwhentheobjectcollideswithaverticalwall.

ReverseVerticalWiththisactionyoureversetheverticalmotionoftheinstance.Thiscanforexamplebeusedwhentheobjectcollideswithahorizontalwall.

SetFrictionFrictionslowsdowntheinstanceswhentheymove.Youspecifytheamountoffriction.Ineachstepthisamountissubtractedfromthespeeduntilthespeedbecomes0.Normallyyouwantaverysmallnumberhere(like0.01).

JumptoPosition

Page 48: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Usingthisactionyoucanplacetheinstanceinaparticularposition.Yousimplyspecifythex-andy-coordinate,andtheinstanceisplacedwithitsreferencepointonthatposition.IfyouchecktheRelativebox,thepositionisrelativetothecurrentpositionoftheinstance.Thisactionisoftenusedtocontinuouslymoveaninstance.Ineachstepweincrementthepositionabit.

JumptoStartThisactionplacestheinstancebackatthepositionwhereitwascreated.

JumptoRandomThisactionmovestheinstancetoarandompositionintheroom.Onlypositionsarechosenwheretheinstancedoesnotintersectanysolidinstance.Youcanspecifythesnappingused.Ifyouspecifypositivevalues,thecoordinateschosenwithbeintegermultiplesoftheindicatedvalues.Thiscouldforexamplebeusedtokeeptheinstancealignedwiththecellsinyourgame(ifany).Youcanspecifyaseparatehorizontalsnappingandverticalsnapping.

AligntoGridWiththisactionyoucanroundthepositionoftheinstancetoagrid.Youcanindicateboththehorizontalandverticalsnappingvalue(thatis,thesizeofthecellsofthegrid).Thiscanbeveryusefultomakesurethatinstancesstayonagrid.

WrapScreenWiththisactionyoucanletaninstancewraparound,thatis,whenitleavesononesideoftheroomitreappearsattheotherside.ThisactionisnormallyusedintheOutsideevent.Notethattheinstancemusthaveaspeedforwrappingtowork,causethedirectionofwrappingisbasedonthedirectionofthemotion.Youcanindicatewhethertowraponlyhorizontal,onlyvertical,orinbothdirections.

MovetoContactWiththisactionyoucanmovetheinstanceinagivendirectionuntilacontactpositionwithanobjectisreached.Iftherealreadyisacollisionatthecurrentpositiontheinstanceisnotmoved.Otherwise,theinstanceis

Page 49: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

placedjustbeforeacollisionoccurs.Youcanspecifythedirectionbutalsoamaximaldistancetomove.Forexample,whentheinstanceisfallingyoucanmoveamaximaldistancedownuntilanobjectisencountered.Youcanalsoindicatewhethertoconsidersolidobjectonlyorallobjects.Youtypicallyputthisactioninthecollisioneventtomakesurethattheinstancestopsincontactwiththeotherinstanceinvolvedinthecollision.

BounceWhenyouputthisactioninthecollisioneventwithsomeobject,theinstancebouncesbackfromthisobjectinanaturalway.Ifyousettheparameterprecisetofalse,onlyhorizontalandverticalwallsaretreatedcorrectly.Whenyousetprecisetotruealsoslanted(andevencurved)wallsaretreatedcorrectly.Thisisthoughslower.Alsoyoucanindicatewhethertobounceonlyagainstsolidobjectsoragainstallobjects.Pleaserealizethatthebounceisnotcompletelyaccuratebecausethisdependsonmanyproperties.Butinmanysituationstheeffectisgoodenough.

Page 50: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Mainactions,set1

Thefollowingsetofactionsdealswithcreating,changing,anddestroyinginstancesofobjects,withsounds,andwithrooms.

CreateInstanceWiththisactionyoucancreateaninstanceofanobject.Youspecifywhichobjecttocreateandthepositionforthenewinstance.IfyouchecktheRelativebox,thepositionisrelativetothepositionofthecurrentinstance.Creatinginstancesduringthegameisextremelyuseful.Aspaceshipcancreatebullets;abombcancreateanexplosion,etc.Inmanygamesyouwillhavesomecontrollerobjectthatfromtimetotimecreatesmonstersorotherobjects.Forthenewlycreatedinstancethecreationeventisexecuted.

CreateMovingThisactionworksthesameastheactionabovebutwithtwoadditionalfields.Youcannowalsospecifythespeedanddirectionofthenewlycreatedinstance.NotethatifyouchecktheRelativebox,onlythepositionisrelative,notthespeedanddirection.Forexample,tomakeabulletmoveinthedirectionofthepersonshootingyouhavetousealittletrick.Aspositionuse0,0andcheckRelative.Asdirectionweneedthecurrentdirectionoftheinstance.Thiscanbeobtainedbytypingintheworddirection.(Thisactuallyisavariablethatalwaysindicatesthecurrentdirectioninwhichtheinstanceismoving.)

CreateRandomThisactionletsyoucreateaninstanceofoneoutoffourobjects.Youspecifythefourobjectsandtheposition.Aninstanceofoneofthesefourobjectsiscreatedatthegivenposition.IfyouchecktheRelativebox,thepositionisrelativetothepositionofthecurrentinstance.IfyouneedachoiceoutoflessthanfourobjectsyoucanuseNoObjectforsomeofthem.Thisisforexampleusefultogeneratearandomenemyatalocation.

ChangeInstance

Page 51: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Withthisactionyoucanchangethecurrentinstanceintoaninstanceofanotherobject.Soforexample,youcanchangeaninstanceofabombintoanexplosion.Allsettings,suchasthemotionandthevalueofvariables,willstaythesame.Youcanindicatewhetherornottoperformthedestroyeventforthecurrentobjectandthecreationeventforthenewobject.

DestroyInstanceWiththisactionyoudestroythecurrentinstance.Thedestroyeventfortheinstanceisexecuted.

DestroyatPositionWiththisactionyoudestroyallinstanceswhoseboundingboxcontainsagivenposition.Thisisuseful,forexample,whenyouuseanexplodingbomb.WhenyouchecktheRelativeboxthepositionistakenrelativetothepositionofthecurrentinstance.

ChangeSpriteUsethisactiontochangethespritefortheinstance.Youindicatewhichnewsprite.Youcanalsoindicatewithsubimagemustbeshown.Normallyyouwoulduse0forthis(thefirstsubimage)unlessyouwanttoseeaparticularsubimage.Use-1ifyoudonotwanttochangethecurrentsubimageshown.Finallyyouchangethespeedoftheanimationofthesubimages.Ifyouonlywanttoseeaparticularsubimage,setthespeedto0.Ifthespeedislargerthanonesubimageswillbeskipped.Ifitissmallerthan1subimageswillbeshownmultipletimes.Don'tuseanegativespeed.Changingspritesisanimportantfeature.Forexample,oftenyouwanttochangethespriteofacharacterdependingonthedirectioninwhichitwalks.Thiscanbeachievedbymakingdifferentspritesforeachofthe(four)directions.Withinthekeyboardeventsforthearrowkeysyousetthedirectionofmotionandthesprite.

TransformSpriteUsethisactiontochangethesizeandorientationofthespritefortheinstance.Usethescalefactorstomakeitlargerorsmaller.Theanglegivesthecounter-clockwiseorientationofthesprite.Forexample,tomakethespriteorientedinthedirectionofmotionuseasavalue

Page 52: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

direction.Forexample,thisisusefulforacar.Youcanalsoindicatewhetherthespriteshouldbemirroredhorizontallyand/orflippedvertically.ThisactionisonlyavailableintheProEdition.

ColorSpriteNormallythespriteisdrawnasitisdefined.Usingthisactionyoucanchangethecolorofthesprite.Thiscolorisblendedwiththesprite,thatis,itiscombinedwiththecolorsofthesprite.Ifyouwanttodrawaspriteindifferentcolorsyoubetterdefinethespriteinblackandwhiteandusetheblendcolortosettheactualcolor.Youcanalsoindicateanalphatransparency.Withavalueof1thespriteisopaque.Withavalueof0itiscompletelytransparent.Withavalueinbetweenyouwillpartiallyseethebackgroundshinethroughit.Thisisgreatformakingexplosions.ThisactionisonlyavailableintheProEdition.

PlaySoundWiththisactionyouplayoneofthesoundresourcesyouaddedtoyourgame.Youcanselectthesoundyouwanttoplayandchoosewhetheritshouldplayonlyonce(thedefault)orloopcontinuously.Multiplewavesoundscanplayatoncebutonlyonemidisoundcanplayatatime.Soifyoustartamidisound,thecurrentmidisoundisstopped.

StopSoundThisactionstopstheindicatedsound.Ifmultipleinstancesofthissoundareplayingallarestopped.

CheckSoundIftheindicatedsoundisplayingthenextactionisperformed.Otherwiseitisskipped.YoucanselectNottoindicatethatthenextactionshouldbeperformediftheindicatedsoundisnotplaying.Forexample,youcancheckwhethersomebackgroundmusicisplayingand,ifnot,startsomenewbackgroundmusic.Notethatthisactionreturnstruewhenthesoundactuallyplaysthroughthespeakers.Afteryoucalltheactiontoplayasounditdoesnotimmediatelyreachthespeakerssotheactionmightstillreturnfalseforawhile.Similar,whenthesoundisstoppedyoustillhearitforawhile(e.g.becauseofecho)andtheactionwillstillreturntrue.

Page 53: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

PreviousRoomMovetothepreviousroom.Youcanindicatethetypeoftransitioneffectbetweentherooms.Youshouldexperimenttoseewhatworksbestforyou.Whentheroomsdonothavethesamesizeyoubetterdonotusetransitions.Ifyouareinthefirstroomyougetanerror.

NextRoomMovetothenextroom.Youcanindicatethetransition.

RestartRoomThecurrentroomisrestarted.Youindicatethetransitioneffect.

DifferentRoomWiththisactionyoucangotoaparticularroom.Youindicatetheroomandthetransitioneffect.

CheckPreviousThisactiontestswhetherthepreviousroomexists.Ifso,thenextactionisexecuted.Younormallyneedthistestbeforemovingtothepreviousroom.

CheckNextThisactiontestswhetherthenextroomexists.Ifso,thenextactionisexecuted.Younormallyneedthistestbeforemovingtothenextroom.

Page 54: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Mainactions,set2

Herearesomemoremainactions,dealingwithtiming,givingmessagestotheuser,anddealingwiththegameasawhole.

SetAlarmWiththisactionyoucansetoneofthetwelvealarmclocksfortheinstance.Youselectthenumberofstepsandthealarmclock.Aftertheindicatednumberofsteps,theinstancewillreceivethecorrespondingalarmevent.YoucanalsoincreaseordecreasethevaluebycheckingtheRelativebox.Ifyousetthealarmclocktoavaluelessthanorequalto0youswitchitoff,sotheeventisnotgenerated.

SleepWiththisactionyoucanfreezethesceneforaparticulartime.Thisistypicallyusedatthebeginningorendofalevelorwhenyougivetheplayersomemessage.Youspecifythenumberofmillisecondstosleep.Alsoyoucanindicatewhetherthescreenshouldfirstberedrawntoreflectthemostrecentsituation.

DisplayMessageWiththisactionyoucandisplayamessageinadialogbox.Yousimplytypeinthemessage.Ifyouusea#symbolinthemessagetextitwillbeinterpretedasanewlinecharacter.(Use\#togetthe#symbolitself.)Ifthemessagetextstartswithaquoteordoublequotesymbol,itisinterpretedasanexpression.Seebelowformoreinformationaboutexpressions.

ShowInfoWiththisactionyoupopupthegameinformationwindow.

RestartGameWiththisactionyourestartthegamefromthebeginning.

EndGameWiththisactionyouendthegame.

Page 55: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

SaveGameWiththisactionyoucansavethecurrentgamestatus.Youspecifythefilenameforsaving(thefileiscreatedintheworkingdirectoryforthegame).Laterthegamecanbeloadedwiththenextaction.(Pleaserealizethatonlythebasicgamestatusissave.Thingsthatareforexamplenotsavedarethecurrentsoundthatisplaying,andadvancedaspectslikethecontentsofdatastructures,particles,etc.)

LoadGameLoadthegamestatusfromafile.Youspecifythefilename.MakesurethesavedgameisforthesamegameandcreatedwiththesameversionofGameMaker.Otherwiseanerrorwilloccur.(Tobeprecise,thegameisloadedattheendofthecurrentstep.Sosomeactionsafterthisonearestillexecutedinthecurrentgame,nottheloadedone!)

Page 56: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Controlactions

Thereareanumberofactionswithwhichyoucancontrolwhichotheractionsareperformed.Mostoftheseactionsaskaquestion,forexamplewhetherapositionisempty.Whentheanswerisyes(true)thenextactionisexecuted,otherwiseitisskipped.Ifyouwantmultipleactionstobeexecutedorskippedbasedontheoutcomeyoucanputtheminablockbyputtingstartblockandendblockactionsaroundthem.Therecanalsobeanelsepartwhichisexecutedwhentheanswerisno.Soaquestiontypicallylooksasfollows:

Herethequestionisaskedwhetherapositionforthecurrentinstanceiscollisionfree.Ifso,theinstancestartsmovinginagivendirection.Ifnot,theinstancejumpstoagivenposition.Notethattheblocksareindented.Thisgivesabetteroverviewoftheactions.(Inparticularwhenyouuseblocksinsideblocks.)Alsoitiseasiertodetectwhenyouforgotastartblockorendblockaction.

ForallquestionsthereisafieldlabeledNOT.Ifyoucheckthisfield,theresultofthequestionisreversed.Thatis,iftheresultwastrueitbecomesfalseandifitwasfalse,itbecomestrue.Thisallowsyoutoperformcertainactionswhenaquestionisnottrue.

Formanyquestionsyoucanindicatethattheyshouldapplytoallinstancesofaparticularobject.Inthiscasetheresultistrueonlyifitis

Page 57: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

trueforallinstancesoftheobject.Forexample,youcancheckwhetherforallballsthepositionslightlytotherightiscollisionfree.

Thefollowingquestionsandrelatedactionsareavailable.(Notethattheyallhaveadifferentlyshapediconandadifferentbackgroundcolorsothattheycanmoreeasilybedistinguishedfromotheractions.)

CheckEmptyThisquestionreturnstrueifthecurrentinstance,placedattheindicatedpositiondoesnotgenerateacollisionwithanobject.Youcanspecifythepositionaseitherabsoluteorrelative.Youcanalsoindicatewhetheronlysolid,orallobjects,shouldbetakenintoaccount.Thisactionistypicallyusedtocheckwhethertheinstancecanmovetoaparticularposition.

CheckCollisionThisisthereverseofthepreviousaction.Itreturnstrueifthereisacollisionwhenthecurrentinstanceisplacedatthegivenposition(again,eitheronlywithsolidobjectsorwithallobjects).

CheckObjectThisquestionreturnstrueiftheinstanceplacedattheindicatepositionmeetsaninstanceoftheindicatedobject.

TestInstanceCountYouspecifyanobjectandanumber.Ifthecurrentnumberofinstancesoftheobjectisequaltothenumberthequestionreturnstrue.Otherwiseitreturnsfalse.Youcanalsoindicatethatthecheckshouldbewhetherthenumberofinstancesissmallerthanthegivenvalueorlargerthanthegivenvalue.Thisistypicallyusedtocheckwhetherallinstancesofaparticulartypearegone.Thisisoftenthemomenttoendaleveloragame.

TestChanceYouspecifythenumberofsidesofadicewhichisthenthrown.Thenifthedicelandsonone,theresultistrueandthenextactionisperformed.Thiscanbeusedtoputanelementofrandomnessinyourgame.Forexample,ineachstepyoucangeneratewithaparticularchanceabomb

Page 58: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

orachangeofdirection.Thelargerthenumberofsidesofthedice,thesmallerthechance.Youcanactuallyuserealnumbers.Forexampleifyousetthenumberofsidesto1.5thenextactionisperformedtwooutofthreetimes.Usinganumbersmallerthan1makesnosense.

CheckQuestionYouspecifyaquestion.Adialogisshowntotheplayerwithayesandanobutton.Theresultistrueistheplayeranswersyes.

TestExpressionThisisthemostgeneralquestionaction.Youcanenteranarbitraryexpression.Iftheexpressionevaluatestotrue(thatis,anumberlargerorequalto0.5)thenextactionisperformed.Seebelowformoreinformationonexpressions.

CheckMouseReturnstrueiftheindicatedmousebuttonispressed.Astandarduseisinthestepevent.Youcancheckwhetheramousebuttonispressedand,ifso,forexamplemovetothatposition(usethejumptoapointactionwithvaluesmouse_xandmouse_y).

CheckGridReturnstrueifthepositionoftheinstanceliesonagrid.Youspecifythehorizontalandverticalspacingofthegrid.Thisisveryusefulwhencertainactions,likemakingaturn,areonlyallowedwhentheinstanceisonagridposition.

StartBlockIndicatesthestartofablockofactions.

EndBlockIndicatestheendofablockofactions.

ElseBehindthisactiontheelsepartfollows,thatisexecutedwhentheresultofthequestionisfalse.

Page 59: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

RepeatThisactionisusedtorepeatthenextaction(orblockofactions)anumberoftimes.Yousimplyindicatethenumber.

ExitEventWhenthisactionisencounterednofurtheractionsinthiseventareexecuted.Thisistypicallyusedafteraquestion.Forexample,whenapositionisfreenothingneedstobedonesoweexittheevent.Inthisexample,thefollowingactionsareonlyexecutedwhenthereisacollision.

Ifyouwantmorecontroloverwhatishappeninginthegameyoucanusethebuilt-inprogramminglanguagethatisdescribedinPart4ofthedocumentation.Ifgivesyoumuchmoreflexibilitythanusingtheactions.Therearealsoactionstodefineandtestvariables.Theyaresimplertousethancodeandcanbeveryusefulforyourgames.Thefollowingactionsdealwiththis.

ExecuteCodeWhenyouaddthisaction,aformshowsinwhichyoucantypeapieceofcodewhichmustbeexecute.Thiscancontainsimplefunctioncallsormorecomplexcode.Usethecodeactionpreferablyonlyforsmallpiecesofcode.ForlongerpiecesyouarestronglyadvisedtousescriptswhicharedescribedinPart2ofthedocumentation.

CommentUsethisactiontoaddalineofcommenttotheactionlist.Thelineisshowninitalicfont.Addingcommentshelpsyourememberwhatyoureventsaredoing.Theactiondoesnotdoanything.Butrealizethatitstillisanaction.Sowhenyouplaceitafteraconditionalactionitistheactionthatisexecutediftheconditionistrue(eventhoughitdoesnotdoanything).

SetVariableTherearemanybuilt-invariablesinthegame.Withthisactionyoucanchangethese.Alsoyoucancreateyourownvariablesandassignvaluestothem.Youspecifythenameofthevariableandthenewvalue.When

Page 60: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

youchecktheRelativebox,thevalueisaddedtothecurrentvalueofthevariable.Pleasenotethatthiscanonlybedoneifthevariablealreadyhasavalueassignedtoit!Seebelowformoreinformationaboutvariables.

TestVariableWiththisactionyoucancheckwhatthevalueofaparticularvariableis.Ifthevalueofthevariableisequaltothenumberprovided,thequestionreturnstrue.Otherwiseitreturnsfalse.Youcanalsoindicatethatthecheckshouldbewhetherthevalueissmallerthanthegivenvalueorlargerthanthegivenvalue.Seebelowformoreinformationaboutvariables.Actually,youcanusethisactionalsotocomparetwoexpressions.

DrawVariableWiththisactionyoucandrawthevalueofavariableataparticularpositiononthescreen.Notethatthiscanonlybeusedinthedraweventofanobject.

Page 61: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Scoreactions

Inmostgamestheplayerwillhaveacertainscore.Alsomanygamesgivetheplayeranumberoflives.Finally,oftentheplayerhasacertainhealth.Thefollowingactionsmakeiteasytodealwiththescore,lives,andhealthoftheplayer.

SetScoreGameMakerhasabuilt-inscoremechanism.Thescoreisnormallydisplayedinthewindowcaption.Youcanusethisactiontochangethescore.Yousimplyprovidethenewvalueforthescore.Oftenyouwanttoaddsomethingtothescore.Inthiscasedon'tforgetthechecktheRelativebox.

TestScoreWiththisquestionactionyoucancheckwhetherthescorehasreachedaparticularvalue.Youindicatethevalueandwhetherthescoreshouldbeequaltothatvalue,besmallerthanthevalueorbelargerthanthevalue.

DrawScoreWiththisactionyoucandrawthevalueofthescoreataparticularpositiononthescreen.Youprovidethepositionsandthecaptionthatmustbeplacedinfrontofthescore.Thescoreisdrawninthecurrentfont.Thisactioncanonlybeusedinthedrawingeventofanobject.

ShowHighscoreForeachgamethetoptenscoresaremaintained.Thisactiondisplaysthehighscorelist.Ifthecurrentscoreisamongthetopten,thenewscoreisinsertedandtheplayercantypehisorhername.Youcanindicatewhatbackgroundimagetouse,whetherthewindowshouldhaveaborder,whatthecolorforthenewentryandtheotherentriesmustbe,andwhichfonttouse.

ClearHighscoreThisactionclearsthehighscoretable.

Page 62: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

SetLivesGameMakeralsohasabuilt-inlivessystem.Withthisactionyoucanchangethenumberoflivesleft.Normallyyousetittosomevaluelike3atthebeginningofthegameandthendecreaseorincreasethenumberdependingonwhathappens.Don'tforgettochecktheRelativeboxifyouwanttoaddorsubtractfromthenumberoflives.Atthemomentthenumberoflivesbecomes0(orsmallerthan0)a"nomorelives"eventisgenerated.

TestLivesWiththisquestionactionyoucancheckwhetherthenumberofliveshasreachedaparticularvalue.Youindicatethevalueandwhetherthenumberoflivesshouldbeequaltothatvalue,besmallerthanthevalueorbelargerthanthevalue.

DrawLivesWiththisactionyoucandrawthenumberoflivesataparticularpositiononthescreen.Youprovidethepositionsandthecaptionthatmustbeplacedinfrontofthenumberoflives.Thenumberoflivesisdrawninthecurrentfont.Thisactioncanonlybeusedinthedrawingeventofanobject.

DrawLifeImagesRatherthandrawingthenumberoflivesleftasanumber,itisoftennicertouseanumberofsmallimagesforthis.Thisactiondoespreciselythat.Youspecifythepositionandtheimageandattheindicatedpositionthenumberoflivesisdrawnasimages.Thisactioncanonlybeusedinthedrawingeventofanobject.

SetHealthGameMakerhasabuilt-inhealthmechanism.Youcanusethisactiontochangethehealth.Avalueof100isconsideredfullhealthand0isnohealthatall.Yousimplyprovidethenewvalueforthehealth.Oftenyouwanttosubtractsomethingfromthehealth.Inthiscasedon'tforgetthechecktheRelativebox.Whenthehealthbecomessmallerorequalto0anoutofhealtheventisgenerated.

Page 63: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

TestHealthWiththisquestionactionyoucancheckwhetherthehealthhasreachedaparticularvalue.Youindicatethevalueandwhetherthehealthshouldbeequaltothatvalue,besmallerthanthevalueorbelargerthanthevalue.

DrawHealthWiththisactionyoucandrawthehealthintheformofahealthbar.Whenthehealthis100thefullbarisdrawn.Whenitis0thebarisempty.Youindicatethepositionandsizeofthehealthbarandthecolorofthebarandthebackground.

ScoreCaptionNormallyinthewindowcaptionthenameoftheroomandthescoreisdisplayed.Withthisactionyoucanchangethis.Youcanindicatewhetherornottoshowthescore,lives,and/orhealthandwhatthecaptionforeachofthesemustbe.

Page 64: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Drawactions

Normallyineachstepofthegame,foreachinstance,itsspriteisdrawnintheroom.Youcanchangethisbyputtingactionsinthedrawevent.(Notethattheseareonlyexecutedwhentheinstanceisvisible!)Thefollowingdrawingactionsareavailable.Theseactionsonlymakesenseinthedrawingevent.Atotherplacestheyarebasicallyignored.

DrawSpriteYouspecifythesprite,theposition(eitherabsoluteorrelativetothecurrentinstanceposition)andthesubimageofthesprite.(Thesubimagesarenumberedfrom0upwards.)Ifyouwanttodrawthecurrentsubimage,usenumber-1.

DrawBackgroundYouindicatethebackgroundimage,theposition(absoluteorrelative)andwhethertheimageshouldbetiledallovertheroomornot.

DrawTextYouspecifythetextandtheposition.A#symbolinthetextisinterpretedasgoingtoanewline.(Use\#togetthe#symbolitself.)Soyoucancreatemulti-linetexts.Ifthetextstartswithaquoteoradoublequote,itisinterpretedasanexpression.Forexample,youcanuse

'X:'+string(x)

todisplaythevalueofthex-coordinateoftheinstance.(Thevariablexstoresthecurrentx-coordinate.Thefunctionstring()turnsthisnumberintoastring.+concatenatesthetwostrings.)

DrawScaledTextThisactionissimilartothepreviousactionbutthistimeyoucanalsospecifyahorizontalandverticalscalingfactortochangethesizeofthetextandyoucanspecifyanangletorotateit.ThisactionisonlyavailableintheProEdition.

Page 65: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

DrawRectangleYouspecifythecoordinatesofthetwooppositecornersoftherectangle;eitherabsoluteorrelativetothecurrentinstanceposition.

HorizontalGradientThisactionalsodrawsarectanglebutthistimeusingagradientcolorthatchangesfromlefttoright.Youspecifytherectangleandthetwocolorstouse.ThisactionisonlyavailableintheProEdition.

VerticalGradientThisactionalsodrawsarectanglebutthistimeusingagradientcolorthatchangesfromtoptobottom.Youspecifytherectangleandthetwocolorstouse.ThisactionisonlyavailableintheProEdition.

DrawEllipseThisactiondrawsanellipse.Youspecifythecoordinatesofthetwooppositecornersofthesurroundingrectangle;eitherabsoluteorrelativetothecurrentinstanceposition.

GradientEllipseAgainanellipseisdrawnbutthistimeyouspecifyacolorforthecenterandtheboundary.ThisactionisonlyavailableintheProEdition.

DrawLineYouspecifythecoordinatesofthetwoendpointsoftheline;eitherabsoluteorrelativetothecurrentinstanceposition.

DrawArrowDrawsanarrow.Youspecifythecoordinatesofthetwoendpointsofthelineandthesizeofthearrowtip.

SetColorLetsyousetthecolorusedfordrawingshapes,lines,andtext.(Itdoesnotinfluencethewayspritesandbackgroundsaredrawn.)

SetFullScreen

Page 66: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Withthisactionyoucanchangethescreenmodefromwindowedtofullscreenandback.Youcanindicatewhethertotogglethemodeorwhethertogotowindowedorfullscreenmode.

TakeSnapshotWiththisactionyoucantakeasnapshotimageofthegameandstoreitina.pngfile.Youspecifythefilenametostoretheimagein.ThisactionisonlyavailableintheProEdition.

CreateEffectWiththisactionyoucancreateallsortsofeffectsinaverysimpleway.Youspecifythetypeofeffect,e.g.anexplosionorsmoke,itsposition,itssizeanditscolorandwhetheritshouldbeshownbelowtheobjectsorontopofthem.Fortherestitworksautomatic.(Forrainandsnowthepositionisirrelevantasitalwaysfallsdownfromthetopofthescreen.Togetcontinuousrainyoushouldcreateitineachstep.)Pleasenotethatbelowactuallymeansatadepthof100000andabovemeansatadepthof-100000.ThisactionisonlyavailableintheProEdition.

Page 67: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Usingexpressionsandvariables

Inmanyactionsyouneedtoprovidevaluesforparameters.Ratherthanjusttypinganumber,youcanalsotypeaformula,e.g.32*12.Butyoucanactuallytypemuchmorecomplicatedexpressions.Forexample,ifyouwanttodoublethehorizontalspeed,youcouldsetitto2*hspeed.Herehspeedisavariableindicatingthecurrenthorizontalspeedoftheinstance.Therearealargenumberofothervariablesthatyoucanuse.Someofthemostimportantonesare:

xthex-coordinateoftheinstanceythey-coordinateoftheinstancehspeedthehorizontalspeed(inpixelsperstep)vspeedtheverticalspeed(inpixelsperstep)directionthecurrentdirectionofmotionindegrees(0-360)speedthecurrentspeedinthisdirectionvisiblewhethertheobjectisvisible(1)orinvisible(0)image_indexthisvariableindicatewhichsubimageinthecurrentspriteiscurrentlyshown.Ifyouchangeitandsetthespeedto0(seebelow)youcandisplayafixedsubimage.image_speedthisvariableindicatesthespeedwithwhichthesubimagesareshown.Thedefaultvalueis1.Ifyoumakethisvaluelargerthan1somesubimagesareskippedtomaketheanimationfaster.Ifyoumakeitsmallerthan1theanimationbecomesslowerbyrepeatingsubimages.scorethecurrentvalueofthescorelivesthecurrentnumberofliveshealththecurrenthealth(0-100)mouse_xx-positionofthemousemouse_yy-positionofthemouse

Youcanchangemostofthesevariablesusingthesetvariableaction.Youcanalsodefineyourownvariablesbysettingthemtoavalue.(Don'tuserelative,becausetheydon'texistyet.)Thenyoucanusethesevariablesinexpressions.Variablesyoucreatearelocaltothecurrent

Page 68: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

instance.Thatis,eachobjecthasitsowncopyofthem.Tocreateaglobalvariable,putthewordglobalandadotinfrontofit.

Youcanalsorefertothevaluesofvariablesforotherobjectsbyputtingtheobjectnameandadotinfrontofthem.Soforexample,ifyouwantaballtomovetotheplacewherethecoinisyoucansetthepositionto(coin.x,coin.y).Inthecaseofacollisioneventyoucanrefertothex-coordinateoftheotherobjectasother.x.Inconditionalexpressionsyoucanusecomparisonslike<(smallerthan),>,etc.

Inyourexpressionsyoucanalsousefunctions.Forexample,thefunctionrandom(10)givesarandomintegernumberbelow10.Soyoucansetforexamplethespeedordirectionofmotiontoarandomvalue.Manymorefunctionsexist.TheyaredescribedinPart4ofthedocumentation.

Page 69: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Creatingrooms

Nowthatyouhavedefinedtheobjectswiththeirbehaviorintheformofeventsandactions,itistimetocreatetheroomsorlevelsinwhichthegametakesplace.Anygamewillneedatleastoneroom.Intheseroomsweplaceinstancesoftheobjects.Oncethegamestartsthefirstroomisshownandtheinstancesinitcometolifebecauseoftheactionsintheircreationevents.

Therearealargenumberofpossibilitieswhencreatingrooms.Besidessettinganumberofpropertiesandaddingtheinstancesoftheobjectsyoucanaddbackgrounds,defineviews,andaddtiles.Mostoftheseoptionsarediscussedlater.Inthischapterwewillonlydiscusssomebasicsettings,theadditionofinstancesofobjects,andthesettingofbackgroundimages.

Tocreatearoom,chooseCreateRoomfromtheResourcesmenu.Thefollowingformwillappear:

Atthetopoftheformthereisatoolbar.Onthisyoucanindicatethesize

Page 70: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ofthegridcellsusedforaligningobjects.Alsoyoucanindicatewhetherornottoshowthegridlinesandwhetherornottoshowthebackgrounds,etc.Itissometimesusefultotemporarilyhidecertainaspectsoftheroom.Realizethoughthatwhenyouareaddinginstancesofobjects,thesewillalwaysbeshown,independentoftheviewsetting.)Therearealsobuttonstoclearallinstancesfromtheroomandtoshiftallinstancesoveranumberofpixels.Usenegativenumberstoshiftthemleftorup.Thisisusefulwhenforinstanceyoudecidedtoenlargetheroom.(Youcanalsousethistoplaceinstancesoutsidetheroom,whichissometimesuseful.).FinallythereistheUndobuttontoundothelastchangetotheroomandtheOKbuttontosavethechanges.(Clickonthecrossatthetoprighttoclosetheformwithoutsavingthechanges.)

Attheleftyouwillseethreetabpages(fiveinadvancedmode).Theobjectstabiswhereyouaddinstancesofobjectstotheroom.Inthesettingstabyoucanindicateanumberofsettingsfortheroom.Inthebackgroundstabyoucansetbackgroundimagesfortheroom.

Addinginstances

Attherightintheroomdesignformyouseetheroom.Atthestartitisempty,withagraybackground.

Page 71: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Toaddinstancestotheroom,firstselecttheobjectstabifthisoneisnotalreadyvisible.Nextselecttheobjectyouwanttoaddbyclickingonthebuttonwiththemenuicon(orbyclickingintheimageareaattheleft).Theimageoftheobjectappearsattheleft.(Notethatwhenyouchangedtheoriginofthespritethereisacrossintheimage.Thisindicateshowtheinstanceswillbealignedwiththegrid.)Nowclickwithyourleftmousebuttonintheroomareaattheright.Aninstanceoftheobjectappears.Itwillsnaptotheindicatedgrid.Ifyouholdthe<Alt>keywhileplacingtheinstanceitisnotalignedtothegrid.Ifyouholddownthemousebuttonwhiledraggingitovertheroom,youmovetheinstancetothecorrectplace.Ifyouholdthe<Shift>keywhilepressingandmovingthemousemultipleinstancesareadded.Withtherightmousebuttonyoucanremoveinstances.Inthiswayyoudefinethecontentsoftheroom.

Asyouwillnotice,ifyouplaceaninstanceontopofanotherone,theoriginalinstancedisappears.Normallythisiswhatyouwant,butnotalways.ThiscanbeavoidedbyuncheckingtheboxlabeledDeleteunderlyingattheleft.

Ifyouwanttochangethepositionofaninstance,holdthe<Ctrl>keyandclickwiththeleftmousebuttonontheinstanceandholddownthebutton.Youcannowdragittoanewposition.(Use<Alt>forprecisepositioning.)

Ifyouholdthe<Ctrl>keywhileclickingwiththerightmousebuttononaninstance,amenuappears.Hereyoucandeletetheobject,typeinaprecisepositionfortheinstance,ormovethebottommostinstanceatthepositiontothetoporsendthetopmostinstancetothebottom.

Roomsetting

Eachroomhasanumberofsettingsthatyoucanchangebyclickingonthesettingstab.

Page 72: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Eachroomhasaname.Bestgiveitameaningfulname.Therealsoisacaption.Thiscaptionisdisplayedinthewindowcaptionwhenthegameisrunning.Youcansetthewidthandheightoftheroom(inpixels).Alsoyoucansetthespeedofthegame.Thisisthenumberofstepspersecond.Thehigherthespeed,thesmootherthemotionis.Butyouwillneedafastercomputertorunit.

Settingthebackground

Withthetabbackgroundsyoucansetthebackgroundimagefortheroom.Actually,youcanspecifymultiplebackgrounds.Thetabpagelooksasfollows:

Page 73: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Atthetopyouwillseethebackgroundcolor.Youcanclickonittochangeit.Thebackgroundcolorisonlyusefulifyoudon'tuseabackgroundimagethatcoversthewholeroom.Otherwise,bestunchecktheboxlabeledDrawbackgroundcolorbecausethiswillbeawasteoftime.

Atthetopyouseealistof8backgrounds.Youcandefineeachofthembutmostofthetimeyouwillneedjustoneortwo.Todefineabackground,firstselectitinthelist.NextchecktheboxlabeledVisiblewhenroomstartsotherwiseyouwon'tseeit.Thenameofthebackgroundwillbecomeboldwhenitisdefined.Nowindicateabackgroundimageinthemenu.Thereareanumberofsettingsyoucanchange.Firstofallyoucanindicatewhetherthebackgroundimageshouldtiletheroomhorizontallyand/orvertically.Youcanalsoindicatethepositionofthebackgroundintheroom(thiswillalsoinfluencethetiling).Adifferentoptionistostretchthebackground.Thebackgroundwillthenbescaledsothatitfillstheentireroom.Theaspectrationoftheimagewillnotbemaintained.Finallyyoucanmakethebackgroundscrollingbygivingitahorizontalorverticalspeed(pixelsperstep).Betternotusescrollingwithastretchedbackground.Theresultwillbeabitjaggy.

ThereisonemorecheckboxlabeledForegroundimage.Whenyoucheckthisbox,thebackgroundisactuallyaforeground,whichisdrawnontopofeverythingelseratherthanbehindit.Clearlysuchanimage

Page 74: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

shouldbepartiallytransparenttobeofanyuse.

Page 75: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Distributingyourgame

Withtheinformationintheprecedingchaptersyoucancreateyourgames.Whenyourgameisfinishedyouobviouslywantotherpeopletoplayit.Youcanofcoursegivethemthe.gmkfilethatyoucreatedandletthemuseGameMakertoplayitbutthisisnormallynotwhatyouwant.Firstofall,youdon'twantotherstobeabletochangethegame,andsecondlyyoualsowantpeopletoplaythegameeveniftheydonothaveGameMaker.Soyouwouldliketocreateastand-aloneexecutableofyourgame.

Creatingstand-aloneexecutablesisveryeasyinGameMaker.IntheFilemenuyouselecttheitemCreateExecutable.Youwillbeaskedforthenameoftheexecutablethatshouldcontainthegame.Indicateaname,pressOKandyouhaveyourstand-alonegamethatyoucangivetoanyoneyoulike.Youcanchangetheiconforthestand-alonegameintheGlobalGameSettings.SeePart3fordetails.

Onceyouhavecreatedastand-aloneexecutableinthewaydescribedaboveyoucangivethisfiletootherpeopleorplaceitonyourwebsitetodownload.YouarefreetodistributethegamesyoucreatewithGameMakerinanywayyoulike.Youcanevensellthem.Thisofcourseassumesthatthesprites,images,andsoundsyouusecanbedistributedorsoldaswell.Seetheenclosedlicenseagreementformoreinformation.

Itisnormallyusefultozipyourexecutable,togetherwithsomereadmeinformation.InWindowsXPandlaterthiscanbedonedirectlythroughtherightmousebuttonmenu,andtherearemanyfreeziputilitiesavailableontheweb.Alternativelyyoucancreateaninstallerforyourgame.Again,alargenumberoffreeinstallationcreationprogramsareavailableontheweb.

IfyouwantyourgametobeplayedbymanymorepeoplewerecommendyoutouploadittotheYoYoGameswebsiteandpresson

Page 76: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

theSharebuttonatthetop.

Page 77: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Advanceduse

ThissectionofthehelpfilegivesyouinformationaboutthemoreadvancedaspectsofGameMaker.

InformationontheadvanceduseofGameMakercanbefoundinthefollowingpages:

AdvancedUserInterfaceMoreaboutSpritesMoreaboutSoundsandMusicMoreaboutBackgroundsMoreaboutObjectsMoreActionsConstantsTriggerEventsIncludingFilesMoreaboutRoomsFontsPathsTimeLinesScriptsExtensionPackagesExportingandImportingResources

Page 78: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Advancedmode

UptonowwehaveonlyconsideredthesimplefeaturesofGameMaker.Buttherearealotmorepossibilities.TobeabletousetheseyoumustrunGameMakerinadvancedmode.Thisiseasytochange.IntheFilemenu,clickonthemenuitemAdvancedmode.(TofullyseetheeffectsyoushouldrestartGameMakeroratleastsaveyourgameandloaditanew.)

WhenyoustartGameMakerinadvancedmode,thefollowingformisshown:

Itcontainsallthatwasthereinsimplemode,butthereareanumberofadditionalresources,buttons,andmenuitems.Also,aswewillseeinthechaptersthatfollow,thedifferentresourceshaveadditionaloptions.Herewewilldiscusstheadditionalmenuitems.

Filemenu

Inthefilemenuyoucanfindthefollowingadditionalcommands:

Page 79: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

PublishyourGame.Thiscommandwilltakeyoutoourwebsitewereyoucaneasilyuploadandpublishyourfinishedgamesuchthateverybodycanplayit.Carefullyfollowtheinstructionstomakeyourgameavailable.Pleaseonlyusethisforfinishedgames,notforpreliminaryversions.ThispossibilityisonlyavailableintheProEdition.ImportResources.Withthiscommandyoucanimportresourcesthatyouexportedwiththenextcommand.SeethesectiononExportingandImportingResourcesformoredetails.ExportResources.Withthiscommandyoucanexportresourcestoafile.SeethesectiononExportingandImportingResourcesformoredetails.Preferences.HereyoucansetanumberofpreferencesaboutGameMaker.TheywillberememberedbetweendifferentcallsofGameMaker.FormoreinformationseethepageonPreferences.

Editmenu

Intheeditmenuyoucanfindthefollowingadditionalcommands:

Addgroup.Resourcescanbegroupedtogether.Thisisveryusefulwhenyoumakelargegames.Forexample,youcanputallsoundsrelatedtoacertainobjectinagroup,oryoucangroupallobjectsthatareusedinaparticularlevel.Thiscommandcreatesanewgroupinthecurrentlyselectedresourcetype.Youwillbeaskedforaname.Groupscanagaincontaingroups,etc.Youcandragresourcesintothegroups.FindResource.Withthiscommandyoutypeinthenameofaresourceanditopenthecorrespondingpropertyform.ExpandResourceTree.Fullyexpandstheresourcetree,showingallresources.CollapseResourceTree.Fullycollapsestheresourcetree,hidingallresources.ShowObjectInformation.Usingthiscommandyoucangetanoverviewofallobjectsinthegame.

Page 80: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Resourcesmenu

Inthismenuyoucannowalsocreatetheadditionalresources.Notethatforeachofthemthereisalsoabuttononthetoolbarandakeyboardshortcut.Therearethreespecialmenuitemsatthebottom:

DefineConstants.Hereyoucandefineconstantsforuseinyourscriptsandactionarguments.FormoreinformationseethesectiononConstants.DefineTriggers.Hereyoucandefineyourowntriggerevents.FormoreinformationseethesectiononTriggerEvents.IncludedFiles.Hereyoucanindicatewhichadditionalfilesshouldbeincludedinthegameexecutable.FormoreinformationseethesectiononIncludingFiles.

Scriptsmenu

Inthescriptsmenuyoucanfindthefollowingadditionalcommands:

ImportScripts.Canbeusedtoimportusefulscriptsfromfiles.ExportScripts.Canbeusedtosaveyourscriptsinafile,tobeusedbyothers.Whenyouselectascriptresourceonlythisscriptissaved.Whenyouselectagroupallscriptsinthegrouparesaved.Whenyouselecttherootresource(oradifferenttypeofresource)allscriptsaresaved.Thismenuitemisalsoavailablewhenright-clickingonascriptorgroupofscripts.ShowBuilt-inVariables.Showsasortedlistofallbuilt-invariables,bothlocalandglobal.ShowBuilt-inFunctions.Showsasortedlistofallbuilt-infunctions.ShowExtensionFunctions.Showsasortedlistofallfunctionsavailableintheextensionpackagesyouincludedinyourgame.ShowConstants.Showsasortedlistofallbuilt-inconstantsandconstantsdefinedinthegameoptions.ShowResourceNames.Showsasortedlistofallresourcenames.Youcanclickonanametoopentheparticularresourceforediting.

Page 81: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

SearchinScripts.Youcansearchforastringinallscripts.Youcanclickononeofthereportedplacestomovethereforediting.CheckResourceNames.Doesacheckofallresourcenames.Nameswillbereportediftheyarenotcorrect,ifthereareduplicateresourcenames,orwhenaresourcenameisthenameofavariable,function,orconstant.Youcanclickonanametoopentheparticularresourceforediting.CheckAllScripts.Checksallscriptsforerrors.Youcanclickononeofthereportedplacestomovethereforediting.

Helpmenu

Hereyoucannowalsofindhelpinformationabouttheextensionpackagesyouareusing.

Page 82: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Preferences

UnderthePreferencesmenuitemintheFilemenuyoucansetanumberofpreferencesthatwillbemaintainedbetweenrunsofGameMaker.Thefollowingpreferencescanbeset:

Generaltab

Showrecentlyeditedgamesinthefilemenu.Ifcheckedtheeightmostrecentlyeditedgamesareshownundertherecentfilesinthefilemenu.Loadlastopenedfileonstartup.IfcheckedwhenyoustartGameMakerthemostrecentlyopenedfileisopenedautomatically.Keepbackupcopiesoffiles.Ifcheckedtheprogramsavesabackupcopyofyourgamewiththeextensiongb0-gb9.YoucanopenthesegamesinGameMaker.Youarestronglyadvisedtouseatleastonebackupcopyforyourwork!Maximumnumberofbackups.Hereyoucanindicatehowmany(1-9)differentbackupcopiesshouldberememberedbytheprogram.Showprogresswhileloadingandsavingfiles.Ifchecked,whenloadorsaveafileaprogressindicatorisshown.

Page 83: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Atstartupcheckfor,andremoveoldtemporaryfiles.GameMakerandgamescreatedwithit,createtemporaryfiles.Normallytheseareautomaticallyremovedbutsometimes,forexamplewhengamescrash,theyareleftbehind.Ifthisoptionischecked,GameMakercheckswhethersuchfilesexistandremovesthematstartup.Don'tshowthewebsiteinthemainwindow.Whencheckedtheimageandlinktothewebsiteonthemainwindowarenotshown.Hidethedesignerandwaitwhilethegameisrunning.Whencheckedthegamemakingprogramishiddenwhileyouaretestingagame.Rungamesinsecuremode.Ifchecked,anygamecreatedwithGameMakerthatrunsonyourmachinewillnotbeallowedtoexecuteexternalprogramsorchangeordeletefilesataplacedifferentfromthegamelocation.(ThisisasafeguardagainstTrojanhorsesalthoughsuccessisnotguaranteed.)Checkingthismeansthatgamesthatutilizesexternalfilesetc.won'tberunningcorrectly.ThesettingonlyworkswhileGameMakerisrunning.SoifyourunthegameindependentlyofGameMaker,forexampleasanexecutablestand-alone,itisNOTruninsecuremode.Shownewsonstartup.WhethertoshowtheGameMakernewsonceadaywhentheprogramisstarted.(CannotbechangedintheLiteEdition.)Shownewsindefaultbrower.WhethertoshowtheGameMakernewsinyourdefaultInternetbrowser,ratherthanintheprogramitself.(CannotbechangedintheLiteEdition.)

Formstab

Page 84: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Showtheorigininthespriteimage.Ifchecked,inthespritepropertiesform,inthespriteimage,theoriginforthespriteisindicated.Inobjectproperties,showhintsforactions.Ifchecked,intheobjectpropertiesform,whenyouholdyourmouseoveroneoftheactions,adescriptionisshown.Whenclosing,removeinstancesoutsidetheroom.Ifchecked,theprogramwarnsyouwhenthereareinstancesortilesoutsidearoomandletsyouremovethem.Rememberroomsettingswhenclosingtheform.Ifchecked,anumberofroomsettings,likewhethertoshowthegrid,whethertodeleteunderlyingobjects,etc.arerememberedwhenyoueditthesameroomlater.

Scriptsandcodetab

Page 85: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thesesettingsrelatetothebuilt-inscriptandcodeeditor.MostofthesesettingsareexplainedindetailinthepageonScripts.Herewejustgiveashortoverview:

GroupundooperationsWhengroupedmultipleactions(liketypingawholeline)becomesoneoperationforundo.NumberofundoYoucanchangethisnumberbutingeneralthisshouldbefine.AutomaticindentationWhensetEnterandBackspacekeyscleverlydealwithindents.IndentamountHowmuchtoindentwitheachtab.SmarttabsWhensettabsgotothepositionbelowthefirstnon-emptyspaceinthepreviousline.AllowcursorbeyondendoflineWhencheckedyoucanplacethecursoratanypositionintheeditorscreen,alsobeyondtheendofline.Ifuncheckedthisisnotpossible.Thisalsochangesthebehavioroftheleftandrightarrowkeys.Showauto-completionoptionsWhensethelpisgivenonwhichfunctionsandvariablesstartwiththelettersyouaretyping.Dealy(msec)Thedelayinmillisecondsbeforethehelpisshown.Sete.g.to0forimmediate.ShowfunctionargumenthelpWhenset,whentypingfunctionarguments,inthestatusbarhelpaboutthisisprovided.ShowfindstringWhenset,whenevertypinginafindstring,alllocationsareshowninthecode.

Page 86: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ShowlinenumbersWhethertheeditorshoulddisplaythelinenumbers.ShowmatchingbracketsWhethertheeditorshouldindicatematchingopenenclosebrackets.ShowcodesnippetswithF2Whenset,pressingF2willbringupanumberofusefulcodesnippets.CheckcodewhiletypingWhensetthecodeisconstantlycheckedanderrorsreported.UsecolorcodingWhethertousecolorcodingintheeditor.ColorsHereyoucansetthecolorsusedforcolorcoding.Youcanalsoresetthedefaultcolors.FontHereyoucanselectthefontfortheeditor.Notethatonlyfixedpitchfontsareshown.Alsonotethatonlythefontandthesizeareused.

Editors

Hereyoucanchoosewhethertousethebuilt-incodeeditor(highlyrecommended)oranexternaleditor.Inthecaseofanexternaleditor,thescripttextissavedasa.txtfileandtheeditoriscalledwiththisfileasanargument.AftereditingityoushouldsavethefileandclosetheeditorsuchthatGameMakercanreadthefilebackin.

Alsoyoucanchoosewhethertousethebuilt-inimageeditor(highly

Page 87: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

recommended)oranexternaleditor.Inthecaseofanexternaleditor,theimageissavedasa.pngfileandtheeditoriscalledwiththisfileasanargument.AftereditingityoushouldsavethefileandclosetheeditorsuchthatGameMakercanreadthefilebackin.

Finallyyoucanindicatethedifferentexternaleditorsforthesoundfilesyouwanttouse.GameMakerdoesnotcontaininternalsoundeditors.Therearethreepossibleeditorshandling.wav,.midand.mp3files.Inthecaseofanexternaleditor,thesoundissavedasa.wav,.mid,or.mp3fileandthecorrespondingeditoriscalledwiththisfileasanargument.AftereditingityoushouldsavethefileandclosetheeditorsuchthatGameMakercanreadthefilebackin.

OtherSettings

ItisalsopossibletochangethelocationofthetempfilesthatGameMakercreatestoe.g.storethegamethatistested.ThislocationcannotbechangedfromthePreferencesbutischangesbycreatingafiletempdir.txtinthefolderwhereGameMakerislocated.Inthisfilethereshouldbeonelinecontainingthelocationofthefolderinwhichthetempfilesarecreates,forexampleC:\GMTEMP.Notethatthenamemustincludethecompletepathandshouldnotendwithabackslash.EachtimeGameMakerisrunauniquetemporaryfolderiscreatedwithinthislocation.Sothingswillworkoutfine,evenwhenmultipleinstancesofGameMakerusethesamelocation.(Notethatthegamesthemselvesalsocreateatempfolderfortheirfiles.Again,thiscanbechangedbycreatingafiletempdir.txtandplacingitinthefolderwherethegameexecutableislocated.)

Secondly,itispossibletochangetheimageGameMakerisusingforthebackgroundofitsmainform.Tothisendplaceanimagefileback.bmpinthefolderwhereGameMakerislocated.

Page 88: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 89: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moreaboutsprites

WhenrunningGameMakerinadvancedmodetheAnumberofadvancedoptionsexist.Whenyouopenthespriteformitwilllookasfollows:

AnewbuttonSaveSpritehasappeared.Withthisbuttonyoucansavethespriteinaproprietaryformat.Thisformatwillnotonlystoretheimage(s)ofthespritebutalsoothersettings,suchascollisionsettingsandtheorigin.Thefilewillhavetheextension.gmspr.GameMakercanloadsuchfilesbutalsothegamescanloadthem.

Atthebottom-left,youcanindicatetheoriginofthesprite.Thisisthepointinthespritethatcorrespondswithitspositionintheroom.Whenyousetaninstanceataparticularposition,theoriginofthespriteisplacedthere.Defaultitisthetopleftcornerofthespritebutitissometimesmoreconvenienttousethecenter(byclickingtheCenterbutton)orsomeotherimportantpoint.Youcanevenchooseanoriginoutsidethesprite.Youcanalsosettheoriginbyclickinginthespriteimage.Theoriginwillbeshownwithacross.

Mostimportantaretheoptionsrelatedtocollisionchecking.Whenevertwoinstancesmeetacollisioneventisgenerated.Collisionsarecheckedinthefollowingway.Eachspritehasamask.Defaultthiscorrespondsto

Page 90: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

allpixelsthatarenotfullytransparent.Whentwopixelsinthemasksofthetwospritesoverlap,acollisionisreported.

Sometimesyoudon'twantprecisecollisionchecking.Inthiscase,unchecktheboxPrecisecollisionchecking.Nowtheboundingboxisusedasthemask.

Whenthespriteshasmultiplesubimages,defaultthereisjustasinglemaskthatcombinesthemasksofallsubimages.Normallythisiswhatyouwantbutincertainsituationsyoumightwanteachsubimagetohaveitsownmask.InthiscasechecktheboxSeparatecollisionmasks.

CollisionMasks

Ifyouwantevenmorecontroloverthecollisionmasks,pressthebuttonModifyMask.Thefollowingwindowwillshow:

Atthelefttopthereisagaintheinformationaboutthespriteimage.Youcanshowthedifferentsubimages.Alsoyoucanindicateherewhethertoshowthecollisionmask(defaulton).Inthiscase,intheimagesattherightthemaskisshownindark.Youcanalsozoominandouttogetabetterview.

Totherightofthisyoucanchangetheboundingbox.Onlypixelsinsidethisboundingboxareusedforthemask.Defaulttheboundingboxis

Page 91: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

automaticallycomputed,takingthealphatoleranceintoaccount,separateforeachsubimage,whenusingseparatecollisionmasks.Youcanalsosetittothefullimageoryoucansetittomanual.Inthelattercaseyoucanspecifytheboundingboxyourself.Whensettomanualyoucanalsodrawtheboundingboxwiththeleftmousebuttonintheimage,oryoucanmoveitwiththerightmousebutton.(Notethoughthatthemaskisshownwhiledrawing,nottheboundingbox!)

Belowthisyoucanindicatetheshapeofthemask.Defaultisprecise,pixel-wisecollisionchecking,butyoucanselectherealsotousetheboundingrectangle,adisk(orellipse)insideit,oradiamondshape.Rectanglesordisksareismanycasesbetterrepresentationsoftheshape.(Notethatthechoicehasnoeffectonspeed!)

Finally,attheleftbottomyoucan(again)indicatewhetherornotthereshouldbeseparatecollisionmasksforallsubimages.(Notethatifyousettheboundingboxmanual,asingleboundingboxwillbeusedforallsubimages,regardlessofthissetting.)Youcanalsoindicatethetolerancewithrespecttothetransparency.Withahighertolerancealsopixelsthatarepartiallytransparentareleftoutsidethemask.Thisinfluencesboththeboundingbox(whennotsettomanual)andthemaskforprecisecollisionchecking.

Itisimportanttocarefullydecideonthecollisionmaskyouuseforyoursprites.Althoughprecisecollisioncheckingmightseemthemostlogicaloption,inmanycasesgameplayisimprovedbyusingboundingboxesordisks,ormasksthatareabitsmallerthantheactualsprites.Ifyouwantevenfurthercontroloverthemask,notethatforobjectsyoucanspecifyadifferentspritetouseasmask.Inthiswayyoucanmakethecollisionmaskcompletelyindependentoftheimage.

Onceyouaredone,pressOK.Ifthemaskwasmodified,thewordModifiedwillshowinthespriteformsuchthatyouareremindedthatyouchangedsomesettingshere.

EditingSprites

Page 92: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

GameMakerhasextensivepossibilitiestocreateandchangeyourownsprites.Informationaboutthiscanbefoundinthefollowingpages:

EditingyourspritesStripsEditingindividualsubimages

Page 93: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Editingyoursprites

Uptonowweloadedourspritesfromfiles.ItisthoughalsopossibletocreateandinparticularmodifythemwithinGameMaker.Todothis,openthespritepropertywindowbydoubleclickingononeofyoursprites(orbycreatinganewone).NowpressthebuttonlabeledEditSprite.Anewformwillappearshowingallthesubimagesthatmakeupthesprite.

Thespriteeditorformwilllookasfollows:

Attherightyouseethedifferentimagesthatmakeupthesprite.NotethatinGameMakerallsubimagesofaspritemusthavethesamesize.Attheleftananimationofthespriteplays.(Ifyoudon'tseetheanimation,checktheboxlabeledShowPreview.)Belowthepreviewyoucanchangethespeedoftheanimationandthebackgroundcolor.Alsoyoucanselectoneofthebackgroundsinyourgameandwhetheritmustbestreched.Inthiswayyoucangetanideaofwhattheanimationwilllooklikeinthegame.(Notethatthisspeedisonlyforpreview.Thespeedoftheanimationduringthegamedependsontheroomspeed.)

Page 94: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thespriteeditorcontainsmanycommandstocreateandchangethesprite.Theseareallgiventhroughthemenus.(Forsometherearebuttonsonthetoolbar.)Somecommandsworkonindividualimages.Theyrequirethatyoufirstselectasubimagewiththemouse.

Filemenu

Thefilemenucontainsanumberofcommandsrelatedtoloadingandsavingsprites.

New.Createsanew,emptysprite.Youmustindicatethesizeofthesprite.(Remember,allimagesinaspritemusthavethesamesize.)CreatefromFile.Createsthespritefromafile.Manyfiletypescanbeused.Theyallcreateaspriteconsistingofasingleimage,exceptforanimatedGIFfilesthataresplitintothesubimagesandstripsthathaveannameendingwith_stripXX.Whenselectingafileyoucanindicatewhethertheimageshouldbeopaque,whethertoremovethebackground,andwhethertosmooththeedge.Youcanselectmultipleimageswhichwillthenallbeloaded.Theyshouldpreferablyhavethesamesize,otherwise,theircanvassizeswillbeadapted.AddfromFile.Addsanimage(ormultipleimages)fromafiletothecurrentsprite.Iftheimagesdonothavethesamesizeyoucanchoosewheretoplacethemortostretchthem.Youcanselectmultipleimageswhichwillthenallbeloaded.Theymustpreferablyhavethesamesize.SaveasPNGFile.SavesthespriteasastripinaPNGfile.Whenthespritehasmultiplesubimagesthetext_stripXXwithXXthenumberofsubimagesisautomaticallyappended.CreatefromStrip.Allowsyoutocreateaspritefromastrip.Seethenextsectionformoreinformation.AddfromStrip.Usethistoaddimagesfromastrip.Seethenextsection.CloseSavingChanges.Closestheform,savingthechangesmadetothesprite.Ifyoudon'twanttosavethechanges,clickontheclosebuttonoftheform.

Page 95: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Editmenu

Theeditmenucontainsthefollowingcommands:

Undo.Undothelastchange.Thelast16changescanbeundone.Redo.Redothelastundonechange.Cut.Cutthecurrentlyselectedsubimagetotheclipboard.Youcaneditorusethesubimageinadifferentprogramthisway.However,thetransparencyinformationmightbelost.Copy.Copythecurrentlyselectedsubimagetotheclipboard.Paste.Pastetheimageontheclipboardasanewsubimage.Whenithasnotthecorrectsizeyoushouldindicatehowtochangethis.Whentheimagecamefromadifferentprogram,transparencyinformationmightbelost.Erase.Erasethecurrent,orallimagestoaparticularcolor.Aformopeninwhichyoucanselectthecolorandtheopacity(alpha)value.Apreviewoftheresultitshown.Youcanindicatewhethertoeraseallimagesoronlythecurrentone.Delete.Deletethecurrentlyselectedsubimage.MoveLeft.Movethecurrentlyselectedsubimageonepositiontotheleftinthesequence.MoveRight.Movethecurrentlyselectedsubimageonepositiontotherightinthesequence.AddEmpty.Addanewemptysubimageattheendofthesequence.InsertEmpty.Insertanewemptysubimagebeforethecurrentlyselectedsubimage.Edit.Editthecurrentlyselectedsubimageusingthebuilt-inimageeditor.SetTranparencyBackground.Hereyoucanindicatehowthetransparentareaofthespritesshouldbeshowninthespriteeditor.Youcaneitherusethe(default)blockpattern,oracolorthatyoucanchangebyclickingonthecolorbox.

Transformmenu

Page 96: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Inthetransformmenuyoucanperformanumberoftransformationsontheimages.Formostofthemyoucanchoosewhethertoapplythemonlytothecurrentsubimageortoallimages.

Shift.Hereyoucanshifttheimage(s)anindicatedamounthorizontallyandvertically.Mirror/Flip.Mirrortheimage(s)horizontallyand/orflipthemvertically.Rotate.Youcanrotatetheimage(s)90,180or270degrees,oranarbitraryamount.Scale.Thiscommandscalestheimage(s)(butnottheimagesize!).Youcanindicatethescalefactorandwhethertoscalehorizontallyand/orvertically.Skew.Thiscommandskewstheimage(s)horizontallyand/orverticallywithagivenamount.ResizeCanvas.Hereyoucanchangethesizeofthecanvas.Youcanalsoindicatewheretheimagesareplacedonthenewcanvas.Stretch.Hereyoucanstretchtheimagesintoanewsize.Youcanindicatethescalefactorandthequality.Crop.Thismakestheimagesassmallaspossible.Thisisveryusefulbecausethelargertheimages,themorevideomemoryGameMakerwilluse.Youcanindicatethesizeofatransparentborderaroundtheimages.Ifyouprovideanegativevalue,theoutsideoftheimageswillbecutoff.

Imagesmenu

Intheimagesmenuyoucanperformanumberofoperationontheimages.SomeoftheseareonlyavailableintheProEdition.

CycleLeft.Cyclesallimagesoneplacetotheleft.Thiseffectivelystartstheanimationatadifferentpoint.CycleRight.Cyclesallimagesoneplacetotheright.BlackandWhite.Makestheimage(s)blackandwhite(thatis,grayscale).Colorize.Hereyoucanchangethecolor(hue)oftheimages.Use

Page 97: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

theslidertopickthenewhue.Whenyouindicatetoshiftthehuethecolorsareshiftedovertheamountindicatedgivingratherinterestingeffects.ColorizePartial.Hereyoucanchangethecolor(hue)ofpartoftheimages.Youcanselecttheoldhueandatolerancearounditandthenindicatethenewhuewithwhichtoreplacethisrangeofcolors.Thiscanbeusedforinstancetochangeonlythecoloroftheshirtsofplayers.Youcanpicktheoldhuealsobyclickingintheleftimage.Intensity.Hereyoucanchangetheintensitybyprovidingvaluesforthecolorsaturationandthevalueofthenewimages.Invert.Invertsthecolorsintheimages.MakeOpaque.Removealltransparencyinformationfromtheimages,makingthemopaque.EraseaColor.Youcanselectacolor(eitherbyclickingonthecolorboxorbyclickingintheleftimage.Alsoyouspecifyatolerance.Allpixelswithacolorclosethetheselectedcolorwillbemadetransparent.SmoothEdges.Smooththeedgesaroundtheopaquepartoftheimage(s)somewhattomakethemlooknicer.(AstrongereffectcanbecreatedbyusingBlurbutonlyblurringthetransparency;seebelow.Opacity.Hereyoucanchangetheopacity(transparency)forthewholeimage.Youcaneithersetitrelativetothecurrentopacityorabsolute.(Fullytransparentpixelsalwaysstayfullytransparent.)SetAlphafromFile.Youselectanimage.Thelightnessofthepixelsofthatimagewillbeusedastransparencyvalue.Blackpixelswillleadtocompletelytransparentpixels,whilewhitepixelswillleadtoopaquepixels.Whentheimagedoesnothavethecorrectsizeitwillbestretched.OnlyavailableintheProEdition.Fade.Hereyouspecifyacolorandanamount.Thepixelsintheimage(s)arenowfadedtowardsthiscolorwiththegivenamount.Blur.Byblurringtheimagesthecolorsaremixedabit,makingitmorevague.Youcanselectasmall,medium,orlargeblur.Alsoyoucanselectwhethertoblurthecolorvaluesand/orthetransparencyvalues.Onlyblurringthetransparencyvaluesisanicewaytosmooththeboundaryoftheimages.Sharpen.Thisissortofthereverseofblurring.Theimagewillbe

Page 98: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

mademoresharp,enhancingtheedges.Youcandoasubtlesharpeningorastrongsharpening.Thespecialsharpeningputsadditionalempasisontheedges,leadingtoafunnyeffect.Youcansharpenthecolorvaluesand/orthetransparencyvalues.Outline.Createanoutlinearoundtheimage.Youareaskedforthecolorandathicknessoftheoutline.Youcanalsoindicatetoplacetheoutlineinsidetheimage.Youcanindicatewhethertoremovetheimageitself,justkeepingtheoutline,andwhethertosmooththeoutline.OnlyavailableintheProEdition.Shadow.Createashadowbehindtheimage.(Thiswillonlyworkwhentheimageispartiallytransparent.)Youindicatethecoloroftheshadowandtheopacity.Alsoyouindicatetherelativepositionoftheshadow.Finallyyoucanindicatewhetheritshouldbeasoftorahardshadow.OnlyavailableintheProEdition.Glow.Createacoloredglowaroundtheimage.Youindicatethecoloroftheglow,theopacityandthethickness.Youcanalsoindicatetoplacetheglowinsidetheimage.OnlyavailableintheProEdition.Buttonize.Turntheimage(s)intoabutton.Youspecifythecolorofthebuttonandtheopacity.Alsoyoumustindicatethethicknessofthebuttonboundaryandwhetheritshouldbesmoothornot.OnlyavailableintheProEdition.GradientFill.Addsagradientfilltotheimage(s).Youspecifythetwocolorsofthefill,theopacity,andthekindoffill.Defaulttheimageisreplacebythegradientalthoughthetransparencyismaintained.ByuncheckingtheReplaceboxthegradientisblendedontotheimage.BycheckingtheChangeTransparencyboxthealphavalueoftheoriginalimageischangedaswell.Youcancreategreateffects.Forexample,makeanimageblack-and-whiteandthenblendagradientonit.OnlyavailableintheProEdition.

Youwillhavetoexperimentwiththesecommandstogetthespritesyouwant.

Animationmenu

Page 99: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Undertheanimationmenuyoucancreatenewanimatedspritesoutofthecurrentsprite.Therearemanyoptionsandyoushouldexperimentabitwiththemtocreatetheeffectsyouwant.Alsodon'tforgetthatyoucanalwayssaveananimatedspriteandlateraddittothecurrentone.Alsoyoucanalwaysaddsomeemptyimagesanddeleteunwantedones.Wewillbrieflygothroughthedifferentpossibilities.

SetLength.Hereyoucanchangethelengthofyouranimation.Theanimationisrepeatedenoughtimestocreatethenumberofframesyouindicate.(Normallyyouwantthistobeamultipleofthecurrentnumberofframes.)Stretch.Thiscommandalsochangesthelengthoftheanimation.Butthistime,framesareduplicatedorremovedtogettherightnumber.Soifyouincreasethenumberofframestheanimationgoesslowerandifyoudecreasethenumberitgoesfaster.Reverse.Well,asyoucouldguessthisreversestheanimation.Soitisplayedbackwards.AddReverse.Thistimethereversesequenceisadded,doublingthenumberofframes.Thisisveryusefulformakinganobjectgoleftandright,changecolorandreturn,etc.Yousometimesmightwanttoremovethedoublefirstandmiddleframethatoccur.TranslationSequence.Youcancreateananimationinwhichtheimageslightlytranslatesineachstep.Youmustprovidethenumberofframesandthetotalamounttomovehorizontallyandvertically.RotationSequence.Createsananimationinwhichtheimagerotates.Youcaneitherchooseclockwiseorcounterclockwiserotation.Specifythenumberofframesandthetotalangleindegrees(360isacompleteturn).(Youmightneedtoresizethecanvasfirsttomakesurethetotalimageremainsvisibleduringtherotation.)Colorize.Createsananimationthatturnstheimageintoaparticularcolor.Fadetocolor.Createsananimationthatfadestheimagetoaparticularcolor.Disappear.Makestheimagedisappearbymakingitmoretransparentineachstep.Shrink.Shrinkstheimagetonothing.Youcanindicatethedirection.Grow.Growstheimagefromnothing.

Page 100: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Flatten.Flattenstheimagetonothinginagivendirection.Raise.Raisestheimagefromagivendirection.Overlay.Overlaystheanimationwithanotherspriteorimageinafile.Youindicatethefileandtheimage(s)fromthatfilearethenplacedontopofthecurrentanimation.Whentheimagefromthefilehasadifferentsizeitisstretched.Morph.Morphstheanimationtoananimationorimagefromafile.Notethatmorphingworksbestifthetwoanimationscoverthesameareaoftheimage.Otherwise,halfwaycertainpixelsdisappearandotherssuddenlyappear.

Inparticularthelasttwocommandsareverypowerful.Forexample,toblowupanobject,addanumberofcopiesandthenanumberofemptyframes.Thenoverlayitwithanexplosionanimation.(Makesurethenumbersofimagesmatch.)Alternatively,morphittotheexplosion.Withsomepracticeyoucanmakegreatsprites.

Page 101: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Strips

Asindicatedabove,spritesarenormallyeitherstoredasanimatedgiffilesorasstripsinPNGfiles,inwhichallsubimagesareplacednexttoeachother.Inthesecondcasethefilenameshouldendwith_stripXXwhereXXindicatesthenumberofsubimages.

However,sometimesspritesarepartofalargerbitmapinwhichthesubimagescanbestorednexttoeachotherorbeloweachotherandmaybethereareseparatinglinesbetweenthem.SuchastripcannotbereadautomaticallyasGameMakerwillnotknowthesizeandpositionofthesubimage.Forexample,thefollowingpieceofastripfilecontainsfourdifferentanimations.

Ifyouwanttopickacertainanimationoutofsuchafileyoumustindicatewheretheimagesare.TothisendyoucanchooseCreatefromStriporAddfromStripfromtheFilemenuinthespriteeditor.Afterindicatingtheappropriatestripimagefile,thefollowingformwillshow:

Page 102: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Attherightyousee(partof)thestripimageyouselected.Attheleftyoucanspecifyanumberofparametersthatspecifywhichsubimagesyouareinterestedin.Notethatoneormorerectanglesintheimageindicatetheimagesyouareselecting.Thefollowingparameterscanbespecified:

Numberofimages.Thisisthenumberofsubimagesyouwanttotakefromthestrip.Imagesperrow.Howmanyimagesoftheonesyouwantarethereperrow.Forexample,bysettingthisto1youwillselectaverticalsequenceofimages.Imagewidth.Widthoftheindividualimages.Imageheight.Heightoftheindividualimages.Horizontalcelloffset.Ifyoudon'twanttoselectthetop-leftimages,youcansetherehowmanyimagesshouldbeskippedhorizontally.Verticalcelloffset.Hereyouindicatehowmanyimagestoskipvertically.Horizontalpixeloffset.Sometimesthereissomeadditionalspaceatthelefttop.Hereyouindicatethisamount(inpixels).YoucanalsousethemousetoindicatetheplacewherethefirstimageshouldstartVerticalpixeloffset.Verticalamountofextraspace.Horizontalseparation.Insomestripstherearelinesoremptyspacebetweentheimages.Hereyoucanindicatethehorizontalamounttoskipbetweentheimages(inpixels).Verticalseparation.Verticalamounttoskipbetweentheimages.

Page 103: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Onceyouselectedthecorrectsetofimages,pressOKtocreateyoursprite.Pleaserememberthatyouareonlyallowedtouseimagescreatedbyotherswhenyouhavetheirpermissionorwhentheyarefreeware.

Page 104: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Editingindividualimages

GameMakerhasabuilt-inimageeditorthatcanbeusedtoeditindividualsubimagesofspritesandbackgroundimages.Tocalltheeditorforasubimageofasprite,selectthesubimageinthespriteeditorandchooseEditImagefromtheImagemenu(ordoubleclickonit).Toeditabackground,openthebackgroundpropertiesforandpressthebuttonEditBackground.

Thebuilt-inimageeditorisprettypowerfulandespeciallysuitedforcreatingspritesandbackgroundsforGameMaker.However,itdoesnothaveallthefeaturesoffull-blownpaintanddrawingpackages.Thebuitl-ineditorisprimarilymeantformakingchangestoimages,notforcreatingspritesandbackgroundsfromscratch.Forthisyouprobablywanttouseaseparatepaintprogram,savetheimagesasPNGfiles,andloadthemintoGameMaker.Youcanalsosetanexternalimageeditorinthepreferences.

Whenyoustarttheimageeditoritwilltypicallylooksasfollows:

Page 105: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Theformshowstheimageinthemiddleandanumberofdrawingtoolsattheleft.Belowthereyoucansetcertainpropertiesofthedrawingtools.Thesewillchangedependingonthetoolyouselect(seebelow).Inthemiddleyouseethecurrentimage.Youcanzoominandoutusingthebuttonsonthetoolbar.Attherightthereisinformationaboutthecolorswithwhichthedraw.Youcansetaseparatecolorfortheleftandtherightmousebutton.Youcanchangethesebyclickingwiththeleftorrightmousebuttoninthecolorselectorimages.Alsoyoucanchangethembyclickingintheboxesatthetopthatrepesentthecolors.BelowthecolorsyouseetheOpacity.Thisindicateshowopaqueortransparentthecoloris.Whenyousetitto255thepixelsyourdrawarefullyopaque.Whenyousetitto0theyarefullytransparent.Normallywhenyoudrawpartiallytransparentpixelstheyareblendedwiththecurrentcolor.BysettingtheColorModetoReplace,thepixelswillbereplacedwiththenewcolor.Finallyatthebottomoftheformthereisastatusbarwithsomeinfomationaboutthecurrentdrawingtool,thepositionofthemouse,thesizeoftheimage,andtheamountofmemoryitrequires.

Drawingtools

Thefollowingdrawingtoolsareavailable(fromlefttoright,toptobottom).

Paint.Withthistoolyoucanpaintontheimage.Youcanusetheleftorrightmousebuttontopaintinthedifferentcolors.Youcanselectthesizeofthepen.Whenholding<Shift>whenstartingtopaintyouonlypainthorizontalorverticallines.Whenholdingthe<Ctrl>keyyoucanselectanewpaintcolor.Spray.Withthistoolyoucansprayontheimage.Sprayislikepaintexceptthatyouuseabrushthatispartiallytransparentatthesides.Youcanusetheleftorrightmousebuttontopaintinthedifferentcolors.Youcanselectthesizeofthebrush.Youcanalsoselectthehardnessofthebrush.Asoftbrushwillbemoretransparentnearthesides.Whenholding<Shift>whenstartingtosprayyouonlypainthorizontalorverticallines.Whenholdingthe<Ctrl>keyyoucanselectanewspraycolor.

Page 106: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Erase.Withthistoolyoucaneraseparttheimage.Itlooksalotlikespraybutyouerasewhatisbelowthemouse.HowmuchyouerasedependsonthetheOpacity.Foravalueof255youerasecompletely.Forasmallervalueyouonlymaketheimageabitmoretransparent.Youcansetthehardnessoftheeraser.Whenholding<Shift>whenstartingtosprayyouonlypainthorizontalorverticallines.ColorPicker.Withthistoolyoucansettheleftorrightmousecolortothecolorofapixelintheimage.Notethatalsotheopacityvalueisset.Line.Withthistoolyoucancandrawstraightlines.Whenholding<Shift>youcandrawhorizontal,vertical,ordiagonallines.Youcansetthewidthofthelineandwhetherisshouldhavearrows.ByselectingAnti-aliasthelineisdrawnwithpartiallytransparentpixelsonthesidetomakeitmoresmooth.Polygon.Withthistoolyoucancandrawaclosedpolygon.Youclickonthepositionofthefirstvertex.Nextyoucaneitherdragthenextvertexorclickonthepositionofthenextvertex.Inthiswayyoucontinue.Youendthepolygonwiththe<Esc>key.Whenholding<Shift>youcandrawhorizontal,vertical,ordiagonallines.Youcansetthewidthofthelineandwhetherthepolygonshouldbefilledornot.ByselectingAnti-aliasthepolygonisdrawnwithpartiallytransparentpixelsonthesidetomakeitmoresmooth.Rectangle.Withthistoolyoucancandrawarectangle.Whenholding<Shift>youcandrawasquare.Whenholding<Ctrl>youdrawtherectanglefromthecenter.Youcansetthewidthofthelineandwhethertherectangleshouldbefilledornot.ByselectingAnti-aliastherectangleisdrawnwithpartiallytransparentpixelsonthesidetomakeitmoresmooth.Ellipse.Withthistoolyoucancandrawanellipse.Whenholding<Shift>youcandrawacircle.Whenholding<Ctrl>youdrawtheellipsefromthecenter.Youcansetthewidthofthelineandwhethertheellipseshouldbefilledornot.ByselectingAnti-aliastheellipseisdrawnwithpartiallytransparentpixelsonthesidetomakeitmoresmooth.RoundedRectangle.Withthistoolyoucancandrawaroundedrectangle.Whenholding<Shift>youcandrawasquare.When

Page 107: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

holding<Ctrl>youdrawtheroundedrectanglefromthecenter.Youcansetthewidthofthelineandwhethertheroundedrectangleshouldbefilledornot.ByselectingAnti-aliastheroundedrectangleisdrawnwithpartiallytransparentpixelsonthesidetomakeitmoresmooth.SelectRegion.Withthistoolyoucancanselectarectangularregion.Youcanextendthecurrentselectionbyholdingthe<Shift>key.Alsoyoucanremovepartsbyholdingthe<Ctrl>key.Onceyoumadeaselectionyoucanpickitupwiththemouseanddragittoanewposition.Whenyouusetherightmousebuttonyoumakeacopy.Theselectioncanalsobecutorcopiedtotheclipboard.Itcanbedeletedwiththe<Del>key.Youcanendtheselectionusingthe<Esc>key.SelectwithMagicWand.Inthiscaseyoumaketheselectionbyclickingonapixel.Allconnectedpixelswiththesamecolorwillbeselected.Youcanindicatethetoleranceincolorvaluwithwhichtoselectpixelsandwhetheronlythecolororalsothetransparencyvalueshouldmatch.Youcanextendthecurrentselectionbyholdingthe<Shift>key.Alsoyoucanremovepartsbyholdingthe<Ctrl>key.Youcanmanipulatetheselectionasabove.SelectbySpraying.Inthiscaseyoumaketheselectionbysprayingwiththemouseontheimage.Youcansetthesizeoftheselector.Fortheresttheselectioncanbetreatedasabove.Differentselectiontypescanbecombined.Text.Toaddatextclickontheimage.Apop-upwindowappearsinwhichyoucanenterthetext.Usethe#symboltoinsertanewline.OnceyoupressOKthetextisputintheimage,withaboxaroundit.Youcannowmovethetextbypressingwiththemouseintheboxanddraggingthetext.Youcanchangethetextbyclickingwiththerightmousebuttoninthebox.YoucansettheFontofthetextandhowthedifferentlinesshouldbealligned.Fill.Clickonapixelintheimageandallconnectedpixelswiththesamecolorwillbeturnedintothenewpixel.Youcansetthetolerancewithwhichthecolorshouldmatch.Alsoyoucansetwhethertoonlymatchonthecolorvalueoralsotakethetransparencyvalueintoaccount.NotthatwhentheColorModeissettoBlendthefillcolorisblendedwiththeexistingone.Toreplace

Page 108: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

it,settheColorModetoReplace.ChangeColor.Clickonapixelintheimageandallpixelsintheimagewiththesamecolorwillbeturnedintothenewpixel.Youcansetthetolerancewithwhichthecolorshouldmatch.Alsoyoucansetwhethertoonlymatchonthecolorvalueoralsotakethetransparencyvalueintoaccount.NotthatwhentheColorModeissettoBlendthenewcolorisblendedwiththeexistingone.Toreplaceit,settheColorModetoReplace.

Menus

Anumberoffurthercommandsisavailablethroughthemenus.Forsomeofthesethereisacorrespondingbuttononthetoolbar.

Filemenu

New.Createsanew,emptyimage.Youmustindicatethesizeoftheimage.(Whentheimageispartofaspritewithmultipleimagesyoucannotsetthesize.)(Remember,allimagesinaspritemusthavethesamesize.)Open.Openanimagefromafile.Thismenuitemisnotavailablewhentheimageispartofaspritewithmultipleimages.PreviousImage.Onlyavailablewhentheimageispartofaspritewithmultipleimages.Savesthechangesandopenstheprevioussubimage.NextImage.Onlyavailablewhentheimageispartofaspritewithmultipleimages.Savesthechangesandopensthenextsubimage.SaveasPNGFile.SavestheimageasaPNGfile.Nootherfileformatsaresupported.CloseSavingChanges.Closestheform,savingthechangesmadetotheimage.Ifyoudon'twanttosavethechanges,clickontheclosebuttonoftheform.

Editmenu

HereyoufindtheusualcommandstoUndothelastchangeandRedo

Page 109: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

thelastundo,todelete,cut,orcopythecurrentselectiontotheclipboard,topastetheimageontheclipboardasaselectionintheimage,andtoselectall.(Notethatwhenusingtheclipboard,transparencyinformationmightbelost.)Twoadditionalcommandsrequireabitmoreexplanation.

ErasetoLeftColor.Thiserasestheimageandreplacesitbytheleftcolor(andopacitysetting).PastefromFile.Youcanselectanimagefromafile.Thisimageisthenpastedintothecurrentimageasaselection.Youcanthenmovethatselectiontotheappropriateplace.

Viewmenu

ZoomOut.Youcanzoomouttoseemoreoftheimage.Youcanalsoholdthe<Ctrl>keyandmovethemousescrollwheeltozoominorout.NoZoom.Setstheimagebacktothenormalsize.ZoomIn.Youcanzoomintomorepreciselydrawinanareaoftheimage.ToggleGrid.Youcantogglethegridonoroff.Notethatthegridisonlyshownwhenyouzoominenough.GridOptions.Hereyoucansetthesizeofthegridandthecolor.Youcanindicatewhethertouseexclusiveorwhendrawingthegrid(mightmakeitmorevisible)andwhetherthedrawingshouldbesnappedtothegrid.ShowPreview.Showapreviewoftheimageintherightbottomcornerinthenormalsize.Thisisinparticularusefulwhenyouarezoominginalottomakesmallchanges.Iftheimageislargerthanthepreviewareyoucanusethemousetodragthepartoftheimageyouwanttosee.Youcanalsodoubleclickonthepreviewimagetoopenaseparatepreviewwindowinwhichyoucanseethecompleteimage.SetTranparencyBackground.Hereyoucanindicatehowthetransparentareaoftheimageshouldbeshowninthespriteeditor.Youcaneitherusethe(default)blockpattern,oracolorthatyoucanchangebyclickingonthecolorbox.

Page 110: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Transformmenu

Thismenucontainsthesametransformationcommandsasinthespriteeditor.Youcanreadabouttheirfunctionthere.NotethatResizeCanvas,Stretch,andCroparenotavailablewhentheimageispartofaspritewithmultipleimages,becauseinthatcasewecannotchangethesizeoftheimage.

Imagemenu

Thismenucontainsthesamecommandsasinthespriteeditor.Youcanreadabouttheirfunctionthere.NotethatsomecommandsareonlyavailableintheProEdition.

Page 111: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moreaboutsoundsandmusic

Inadvancedmodeyouhavealotmorecontroloverthesoundsandpiecesofmusicyouaddtoyourgame.Whenyouaddasoundresourcethefollowingformwillshow:

Besidesthebuttonstoload,save,andplaysoundstherearealotofsettingsnowthatwillbediscussedhere.

Firstofallyoucanindicatethekindofsound.Fourkindsarepossible.Normalsoundsareingeneralusedforsoundeffectsinwavefiles(althoughtheycanbeusedformidifilesaswell).Multiplenormalsoundscanplayatthesametime.Youcanevenplaymultiplecopiesofthesamesoundsimultaneously.Backgroundmusicissimilartonormalsoundsbutonlyonecanplayatanymoment.Soonceyoustartanewbackgroundsound,thecurrentlyplayingonewillbestopped.Midifilesaredefaultbackgroundmusic.3Dsoundissoundforwhichyoucanapply3Dsettingsthroughspecialfunctions.Youwillonlyneedtheseforadvancedsoundeffects.

SoundfilesarenormallyplayedthroughDirectX.Thisgivesmany

Page 112: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

possibilitiesbutislimitedtowaveandmidifiles.Ifyouwanttoplayotherfiles,likemp3files,youshouldselecttheoptiontousethemediaplayer.Thisismuchmorelimitedthough.Novolumechangesoreffectscanbeusedandonlyonepiececanplayatonce.Notethatmidifiles,whenplayedthroughthemediaplayermaysounddifferentfromplayingthemasbackgroundornormalsounds.Thereasonisthatthemediaplayerusesthehardwaresynthesizer(whichisdifferentoneachmachine)whileotherwiseasoftwareversionisused(whichsoundsthesameonallmachines).Preferablydon'tusemp3filesinyougames.Theyneedtobedecompressedwhichtakesprocessingtimeandmightslowdownthegame.Thefactthatthefilesizeissmallerdoesnotmeanthattheyuselessmemory.Also,notallmachinessupportthem.Soyourgamemightnotrunonallmachines.

Secondly,youcanindicatesomesoundeffects,likechorusorecho(onlyintheProEditionofGameMaker!)Youcanselectanycombination.Youcanimmediatelylistentotheresults.(WhenusingGMLcodeyoucanevenchangetheparametersoftheseeffects.)

Alsoyoucanindicatethedefaultvolumeofthesoundandwhethertopanittotheleftortherightspeaker.

Forallsoundsyoucanindicatewhethertheyshouldbepreloadedornot.Whenasoundisplayeditmustbeloadedintoaudiomemory.Ifyoupreloadthesoundthisisdoneatthestartofthegame,makingitimmediatelyavailableforplayback.Whennot,itisloadedthefirsttimeitisused.Thiswillsavememorybutmightgiveasmalldelaythefirsttimethesoundisused.

GameMakerdoesnothaveabuilt-insoundeditor.Butinthepreferencesyoucanindicateexternaleditorsthatyouwanttouseforeditingsounds.IfyouselectedtheseyoucanpressthebuttonlabeledEditSoundtoeditthecurrentsound.(TheGameMakerwindowwillbehiddenwhileyoueditthesoundandreturnswhenyouclosethesoundeditor.)

Page 113: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 114: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moreaboutbackgrounds

Inadvancedmorethereareanumberofadditionaloptionsforbackground.Firstofall,anewbuttonSaveBackgroundhasappeared.Withthisbuttonyoucansavethebackgroundinaproprietaryformat.Thiswillnotonlystoretheimageitselfbutalsoforexampleinformationaboutthetiles(seebelow).Thesefileswillhavetheextension.gmbck.YoucanloadtheminGameMakerandwhilerunningagame.AlsoyoucanalsochangeabackgroundorcreateyourownbackgroundsbypressingthebuttonlabeledEditBackground.Abuilt-inimageeditoropensthathasmanyfeatures.Pleaserealizethatthisisnotafull-blownprogramandifyourequiremoreadvancededitingtoolsyoumightwanttouseaseparatedrawingprogram.FormoreinformationonhowtousetheimageeditorseethesectiononEditingimages.

Sometimesyouwanttouseabackgroundasasetoftiles,thatis,acollectionofsmallerimagesinonebigimage.Whencreatetheroomsyoucanthenaddthesesubimagesatdifferentplacesintheroom.Thisisveryusefulforcreatingnicelookinglevels.Touseabackgroundasatileset,checktheboxlabelledUseastileset.Theformnowchangestolookasfollows:

Youcanindicateanumberofsettingsforthetileset.Inparticularyoucanindicatethewidthandheightofeachtile.(Onlyonesizecanbegiven,sobettermakesurethatalltilesinthesethavethesamesize.Ifyouhavedifferentsizes,createtwoormoretilesets.)Youcanalsoindicatean

Page 115: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

offsetwherethetopleftmosttilestarts.Finally,aseparationbetweenthetiles(thisisnormally0or1)canbeindicated.Formoreinformationonusingtiles,seethesectiononAddingTileswhencreatingrooms.

Awordofwarningisrequiredhere.Whenyouputseparatingbordersbetweenthespritesanduseinterpolationbetweenpixels(seetheglobalgamesettings)thiscanresultincracksbetweenthetiles.Bettermakesurethepixelsaroundthetilesactuallymatchwiththepixelsjustinsidethetilestoavoidthis.Youcaneasilyachievethisbyeditingthebackgroundandchangingthecolorofsuchpixels.

Page 116: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moreaboutobjects

Whenyoucreateanobjectinadvancedmode,youcanchangesomemoreadvancedsettings.

Depth

Firstofall,youcansettheDepthoftheinstancesoftheobject.Whentheinstancesaredrawnonthescreentheyaredrawninorderofdepth.Instanceswiththelargestdeptharedrawnfirst.Instanceswiththesmallestdeptharedrawnlast.Wheninstanceshavethesamedepth,theyaredrawnintheorderinwhichtheywerecreated.Ifyouwanttoguaranteethatanobjectliesinfrontoftheothersgiveitanegativedepth.Ifyouwanttomakesureitliesbelowotherinstances,giveitalargepositivedepth.Youcanalsochangethedepthofaninstanceduringthegameusingthevariablecalleddepth.

Persistentobjects

Secondly,youcanmakeanobjectpersistent.Apersistentobjectwillcontinueexistingwhenyoumovefromoneroomtothenext.Itonlydisappearswhenyouexplicitlydestroyit.Soyouonlyneedtoputaninstanceoftheobjectinthefirstroomandthenitwillremainavailableinallrooms.Thisisgreatwhenyouhaveamaincharacterthatmovesfromroomtoroom.Usingpersistentobjectsisapowerfulmechanismbutalsoonethateasilyleadstoerrors.

Parents

Everyobjectcanhaveaparentobject.Whenanobjecthasaparent,itinheritsthebehavioroftheparent.Stateddifferently,theobjectisasortofspecialcaseoftheparentobject.Forexample,ifyouhave4different

Page 117: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

balls,namedball1,ball2,ball3andball4,whichallbehavethesamebuthaveadifferentsprite,youcanmakeball1theparentoftheotherthree.Nowyouonlyneedtospecifyeventsforball1.Theotherswillinherittheeventsandbehaveexactlythesameway.Also,whenyouapplyactionstoinstancesoftheparentobjecttheywillalsobeappliedtothechildren.So,forexample,ifyoudestroyallball1instancestheball2,ball3,andball4instanceswillalsobedestroyed.Thissavesalotofwork.

Often,objectsshouldbehavealmostidenticallybuttherewillbesomesmalldifferences.Forexample,onemonstermightmoveupanddownandtheotherleftandright.Fortheresttheyhaveexactlythesamebehavior.Inthiscasealmostalleventsshouldhavethesameactionsbutoneortwomightbedifferent.Againwecanmakeoneobjecttheparentoftheother.Butinthiscasewealsodefinecertaineventsforthechildobject.Theseevents"override"theparentevents.Sowheneveraneventforthechildobjectcontainsactions,theseareexecutedinsteadoftheeventoftheparent.Ifyoualsowanttoexecutetheparenteventyoucancalltheso-called"inherited"eventusingtheappropriateaction.

Itisactuallygoodpracticeinsuchcasestocreateonebaseobject.Thisbaseobjectcontainsallthedefaultbehaviorbutisneverusedinthegame.Allactualobjectshavethisbaseobjectasparent.Parentobjectscanagainhaveparents,andsoon.(Obviouslyyouarenotallowedtocreatecycles.)Inthiswayyoucancreateanobjecthierarchy.Thisisextremelyusefultokeepyourgamestructuredandyouarestronglyadvisedtolearntousethismechanism.

Thereisalsoaseconduseoftheparentobject.Italsoinheritsthecollisionbehaviorforotherobjects.Letusexplainthiswithanexample.Assumeyouhavefourdifferentfloorobjects.Whenaballhitstheflooritmustchangedirection.Thishastobespecifiedinthecollisioneventoftheballwiththefloor.Becausetherearefourdifferentfloorsweneedtoputthecodeonfourdifferentcollisioneventsoftheball.Butwhenyoumakeonebasefloorobjectandmakethisonetheparentofthefouractualfloorobjects,youonlyneedtospecifythecollisioneventwiththisbasefloor.Theothercollisionswillperformthesameevent.Again,thissavesalotofcopying.

Page 118: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Asindicated,whereveryouuseanobject,thisalsoimpliesthedescendants.Thishappenswhen,inanaction,youindicatethattheactionmustbeappliedtoinstancesofacertainobject.Italsohappenswhenyouusethewith()statementincode(seebelow).Anditworkswhenyoucallfunctionslikeinstance_position,instance_number,etc.Finally,itworkswhenyourefertovariablesinotherobjects.Intheexampleabovewhenyousetball1.speedto10thisalsoappliestoball2,ball3andball4.

Masks

Whentwoinstancescollideacollisioneventoccurs.Todecidewhethertwoinstancesintersect,thespritesareused.Thisisfineinmostcases,butsometimesyouwanttobasecollisionsonadifferentshape.Forexample,ifyoumakeanisometricgame,objectstypicallyhaveaheight(togivethema3Dview).Butforcollisionsyouonlywanttousethegroundpartofthesprite.Thiscanbeachievedbycreatingaseparatespritethatisusedascollisionmaskfortheobject.

Information

ThebuttonShowInformationgivesanoverviewofallinformationfortheobjectthatcanalsobeprinted.Thisisparticularlyusefulwhenyoulooseoverviewofallyouractionsandevents.

Page 119: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moreactions

Inadvancedmodethereareanumberofadditionalactionsavailablewhichwillbedescribedhere.

Informationonthedifferentadditionalactionscanbefoundinthefollowingpages:

MoreMoveActionsMoreMainActionsMoreControlActionsMoreDrawActionsParticleActionsExtraActions

Page 120: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moremoveactions

Someadditionalmoveactionsareavailableinadvancedmode.Thefollowingactionsareadded:

SetPathWiththisactionyoucanspecifythattheinstanceshouldfollowaparticularpath.Youindicatethepaththatmustbefollowedandthespeedinpixelsperstep.Whenthespeedispositivetheinstancestartsatthebeginningofthepath.Ifitisnegativeitstartsattheend.Nextyouspecifytheendbehavior,thatis,whatshouldhappenwhentheendofthepathisreached.Youcanchoosetostopthemotion,restartfromthebeginning,restartfromthecurrentposition(whichisthesamewhenthepathisclosed),orreversethemotion.Finallyyoucanindicatethatthepathmustbeseenasabsolute,thatis,thepositionwillbeasindicatedinthepath(thisisusefulwhenyouhavedesignedthepathataparticularplaceintheroom)orrelative,inwhichcasethestartpointofthepathisplacedatthecurrentlocationoftheinstance(endpointwhenspeedisnegative).Seethechapteronpathsformoreinformation.

EndPathUsethisactiontostopthepathfortheinstance.

PathPositionWiththisactionyoucanchangethecurrentpositionoftheinstanceinthepath.Thismustbeavaluebetween0and1(0=beginning,1=end).

PathSpeedWiththisactionyoucanchangethespeedoftheinstanceonthepath.Anegativespeedmovestheinstancebackwardsalongthepath.Setitto0totemporarilystopthemotionalongthepath.

StepTowardsThisactionshouldbeplacedinthestepeventtolettheinstancetakeasteptowardsaparticularposition.Whentheinstanceisalreadyatthepositionitwillnotmoveanyfurther.Youspecifythepositiontomoveto,

Page 121: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

thespeedwithwhichtomove,thatis,thesizeofthestep,andwhetherthemotionshouldstopwhenhittingasolidinstanceorwhenhittinganyinstance.

StepAvoidingThisisaverypowerfulmotionaction.Itshouldbeplacedinthestepevent.Likethepreviousactionitletstheinstancetakeasteptowardsaparticularposition.Butinthiscaseittriestoavoidobstacles.Whentheinstancewouldrunintoasolidinstance(oranyinstance)itwillchangethedirectionofmotiontotrytoavoidtheinstanceandmovearoundit.Theapproachisnotguaranteedtoworkbutinmosteasycasesitwilleffectivelymovetheinstancetowardsthegoal.Formorecomplicatedcases,therearemotionplanningfunctions.Youspecifythepositiontomoveto,thespeedwithwhichtomove,thatis,thesizeofthestep,andwhetherthemotionshouldavoidsolidinstancesoranyinstance.

Page 122: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moremainactions

Someadditionalmainactionsareavailableinadvancedmode.Thefollowingactionsareadded:

SetTimeLineWiththisactionyousettheparticulartimelineforaninstanceofanobject.Youindicatethetimelineandthestartingpositionwithinthetimeline(0isthebeginning).Alsoyouindicatewhetherthetimelineshouldstartimmediatelyandwhetheritshouldloopattheend.

TimeLinePositionWiththisactionyoucanchangethepositioninthecurrenttimeline(eitherabsoluteorrelative).Thiscanbeusedtoskipcertainpartsofthetimelineortorepeatcertainparts.

TimeLineSpeedWiththisactionyoucanchangethespeedofthetimeline(eitherabsoluteorrelative).Aspeedof1isthenormalspeed.Whenyoue.g.setitto2theactionswillhappentwiceasfastandwhenyousetitto0.5twiceasslow.Youcanalsosetanegativespeed,inwhichcasethetimelineisplayedbackwards.

StartTimeLineThisactionstartsthetimelinefromitscurrentposition(ifitispausedorstopped).

PauseTimeLineThisactionpausesthetimeline.Usethestartactiontoletitcontinue.

StopTimeLineThisactionstopsthetimelineandsetsthepositionbackto0.

SplashTextWiththisactionyoucanshowatextfile.Thiscaneitherbea.txtfileora.rtf(RichTextFormat)file(noimagesorembeddedobjectsareshown

Page 123: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

though).Youspecifythefilename.Makesurethefileexists.YoushouldeitherdistributeitwiththegameorincludeitinthegamethroughIncludeFilesintheResourcesmenu.(Notethatnoscrollbarwillbeshownnoristhereanotherwaytoscrollthetext.Sothetextmustfitthewindow.)ThisactionisonlyavailableintheProEdition.

SplashImageWiththisactionyoucanshowanimagefile.Mostcommonimagefiletypesaresupported.Youspecifythefilename.Makesurethefileexists.YoushouldeitherdistributeitwiththegameorincludeitinthegamethroughIncludeFilesintheResourcesmenu.Youcane.g.usethistocreateaseriesofimagesashelpforyourgame.Notincludingtheimagesinthegameitselfwillreducegamesizeandimprovegameloadingtime.ThisactionisonlyavailableintheProEdition.

SplashWebpageWiththisactionyoucanshowawebpage.Youprovidetheurlandwhetheritshouldbeshowninthegamewindoworinthedefaultwebbrowser.Theurlcanbetheaddressofawebsite,forexamplehttp://www.yoyogames.com)orcanbethefilenameforalocalhtmlfile.Notehoweverthatyoumustprovidethefullpathforthistowork(whichisnotthecasefortheothersplashactions).Soyoubestuseasurlsomethinglike""+working_directory+"\index.html".(Thefirsttwoquotesarerequiredtoindicatethisisanexpressionratherthanastring.)YoushouldeitherdistributethefilewiththegameorincludeitinthegamethroughIncludeFilesintheResourcesmenu.Youcane.g.usethistocreatefancyhelppagesforyourgame.ThisactionisonlyavailableintheProEdition.

SplashVideoWiththisactionyoucanshowavideo/moviefile.Youspecifythefilenameandwhetherismustbelooped.Makesurethevideofileexists.YoushouldeitherdistributeitwiththegameorincludeitinthegamethroughIncludeFilesintheResourcesmenu.ThisactionisonlyavailableintheProEdition.

SplashSettings

Page 124: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Withthisactionyoucanchangecertainsettingsforthesplashscreensthatyoudisplaywiththepreviousactions.Youcanprovidethecaptionforthehelpwindow(onlywhenitisshowninaseparatenormalwindow),youcanindicatewherethesplashscreensmustbeshown(insidethegamewindow,inanormalwindow,orfullscreen),youcanindicatewhetheraclosebuttonmustbeshowninthetoprightcornerofthesplashscreenandwhetherpressingtheescapekeyorclickingwithamouseinthesplashscreenwillclosethesplashscreen.(Forwebpagesclickingwiththemousewillnotworknorwilltheescapekeyworkunlesstheclosebuttonisshown.)ThisactionisonlyavailableintheProEdition.

ReplaceSpriteThisactioncanbeusedtoreplaceaspritefromthecontentsofafile.Youindicatethespriteyouwanttoreplace,thefilenameandthenumberofsubimagesinthesprite.Manydifferentimagesfileformatsaresupported,e.g..bmp,.jpg,.tif,and.gif.Foragiffilethenumberofsubimagesisautomaticallydecidedbasedonthenumberofsubimagesinthegiffile.Othersettingsforthesprite,e.g.whetheritistransparentornot,arenotchanged.Youcanusethisactiontoavoidstoringallspritesintheprogramitself.Forexample,atthebeginningofalevelyoucanreplacespritesbytheactualcharacterspritesyouwanttouse.DON'Tchangeaspritethatisatthatmomentbeingusedinaninstanceintheroom.Thismightgiveunwantedeffectswithcollisions.ThisactionisonlyavailableintheProEdition.

ReplaceSoundWiththisactionyoucanreplaceasoundbythecontentsofafile(.wav,.mid,or.mp3).Youspecifythesoundandthefilename.Thisavoidshavingtostoreallthesoundsinthegameitself.Forexample,youcanusedifferentpiecesofbackgroundmusicandpicktheoneyouwanttoplay.DON'Tchangeasoundwhileitisplaying.ThisactionisonlyavailableintheProEdition.

ReplaceBackgroundWiththisactionyoucanreplaceabackgroundbythecontentsofafile.Manydifferentimagesfileformatsaresupported,e.g..bmp,.jpg,.tif,and

Page 125: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

.gif.Youspecifythebackgroundandthefilename.Thisavoidshavingtostoreallthebackgroundsinthegameitself.DON'Tchangeabackgroundthatisvisible.ThisactionisonlyavailableintheProEdition.

Page 126: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Morecontrolactions

Someadditionalcontrolactionsareavailableinadvancedmode.Thefollowingactionsareadded:

ExecuteScriptWiththisactionyoucanexecuteascriptthatyouaddedtothegame.Youspecifythescriptandthemaximal5argumentsforthescript.

CallParentEventThisactionisonlyusefulwhentheobjecthasaparentobject.Itcallsthecorrespondingeventintheparentobject.

Page 127: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moredrawactions

Thefollowingadditionaldrawactionisavailableinadvancedmode:

SetFontYoucansetthefontthatisfromthismomentonusedfordrawingtext.Thismustbeoneofthefontresourcesyouhavedefine.IfyouchooseNoFontadefault12pointArialfontisused.

Page 128: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Particleactions

AsetofactiondealingwithparticlesisavailableontheExtratab.TheseactionsareonlyavailableintheProEditionofGameMaker.

Particlesystemsaremeanttocreatespecialeffects.Particlesaresmallelements(representedbyapixeloralittleshape).Suchparticlesmovearoundaccordingtopredefinedrulesandcanchangecolorwhiletheymove.Manysuchparticlestogethercancreatee.g.fireworks,flames,rain,snow,starfields,flyingdebris,etc.

GameMakercontainsanextensiveparticlesystemthatcanbeaccessedthroughfunctions.Amorelimitedparticlesystemcanbeaccessedthroughtheactionsdescribedbelow.

Aparticlesystemcandealwithparticlesofdifferenttypes.Aftercreatingtheparticlesystemthefirstthingtodoisspecifytheparticletypes.Usingtheactionsbelowyoucanspecifyupto16typesofparticles.Eachtypehasashape,asize,astartcolorandanendcolor.Thecolorslowlychangesfromthestartcolortotheendcolor.Particleshavealimitedlifetime.Inthetypeyouspecifytheminimalandmaximallifetimeoftheparticles.Particlesalsohaveaspeedandadirection.Finally,gravityandfrictioncanworkonparticles.

Afteryouspecifytheparticletypesyoumustcreatethematplacesintheroom.Youcaneitherburstanumberofparticlesofaparticulartypefromaplaceoryoucancreateaconstantstreamofparticlesappearing.Particlesappearatemitters.Theparticlesystemcanhaveupto8

Page 129: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

emittersworkingatthesametime.Soafteryoucreatetheparticletypesyoumustcreatetheemittersandtellthemtoburstorstreamparticles.

Hereisthecompletesetofactions.Bestexperimentwiththemtogettherequiredeffect.

CreatePartSystemThisactioncreatestheparticlesystem.Itmustbecalledbeforeanyotheractionscanbeused.Youonlyneedtocallitonce.Youcanspecifythedepthatwhichtheparticlesaredrawn.Ifyouusealargepositivedepththeparticlesappearbehindtheinstances.Ifyouuseanegativedepththeyappearinfrontoftheinstances.

DestroyPartSystemThisactiondestroystheparticlesystem,freeingallitsmemory.Don'tforgettocallthis(e.g.whenyoumovetoadifferentroom)becauseparticlesystemsusealotofstorage.

ClearPartSystemThisactionremovesalltheparticlescurrentlyvisible.Itdoesnotstoptheemitterssonewparticlesmightbecreatedagainifyouhavestreamingemitters(seebelow).

CreateParticleWiththisactionyoucreateaparticletype.Youcanchooseoneofthe16typesavailable.Fortheparticletypeyoucanspecifyitsshapeorthespritetobeusedforit.Ifyouspecifyaspritethespritewillbeused.Ifyousetthespritetonosprite,theshapewillbeused.Thereareanumberofinterestingbuilt-inshapes.Youalsoindicateditsminimalandmaximalsize(whentheparticleappearsarandomvaluebetweentheseboundsisused).Finallyyouspecifytheincreaseinsizeineachstep.Foradecrease,useanegativevalue.Notethatonlyaparticletypeiscreated,notanactualparticle.Forthisyouneedemitters(seebelow).

ParticleColorAparticlecanhaveacolor(defaultthecoloriswhite).Withthisactionyoucansetthecolortobeusedforaparticulartype.Youmustindicatetheparticletypethecolorisdefinedfor.Nextyouspecifyhowacoloris

Page 130: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

applied.Eitherarandomcolorischoosenbetweentwogivencolors,orthecolorstartswiththefirstcolorandthangraduallyoverthelifetimeoftheparticle,itchangestothesecondcolor.Bothcolorsmustbegiven.Finallyyoucanindicatethealphatransparency.Youspecifythetransparencyatthemomenttheparticleiscreatedandwhenitdies.Thetransparencyslowlychangesbetweenthesevalues.Itisnormallynicetodecreasethealphavalueoverthelifetimeofaparticle.

ParticleLifeAparticlelivesforalimitednumberofsteps.Afterthisisdisappears.Withthisactionyousetthelifetimeforaparticletype.Yougivetwolimitingvaluesandtheactuallifetimeischosenrandomlybetweenthem.

ParticleSpeedWiththisactionyoucansetthespeedanddirectionofmotionforaparticletype.Againyougivetwolimitsandtheactualvalueischosenrandomlybetweenthem.Forexample,tomaketheparticlemoveinarandomdirection,give0and360forthelimitsforthedirection.Youcanalsospecifyafriction.Thisamountissubtractedfromthespeedineachstepuntilitbecomes0.(Youcanmakeaparticlespeedupbyusinganegativefriction.)

ParticleGravityWiththisactionyousettheamountofgravityanddirectionofgravityforaparticularparticletype.270isdownwards.

ParticleSecondaryThisisabitmorecomplicated.Particlescancreateotherparticlesduringtheirlifetimeandwhentheydie.Withthisactionyoucanspecifythis.Youcandefinethetypeandnumberofparticlesthatmustbecreatedateachstepduringthelifetimeandyoucanspecifythetypeandnumberofparticlesthatmustbecreatedwhentheparticledies.Beverycarefulhere.Youcaneasilycreatehugenumbersofparticlesinthisway,slowingdownthesystemconsiderably.Forthenumbersyoucanalsouseanegativevalue.Anegativevaluexmeansthatineachstepaparticleiscreatedwithchance-1/x.Soforexample,ifyouwanttogenerateasecondaryparticleaboutevery4steps,useavalueof-4.

Page 131: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Secondaryparticlesaregreatforcreatingeffectsliketailsofparticlesorexplodingparticles.

CreateEmitterThisactioncreatesaparticleemitter.Particlesaregeneratedbyemitters.Youcanhaveuptoeightemitters.Choosetheemitterandspecifytheshapeofitanditssizeandposition(intheformofaboundingbox).

DestroyEmitterThisactiondestroystheindicatedemitter.Notethatexistingparticlesthatcamefromthisemitterarenotremoved.

BurstfromEmitterEvenifyoudefinedaparticletypeandanemittertherearestillnoparticles.Youstillhavetotelltheemittertogeneratetheparticles.Withthisactionyoutellaparticularemittertogenerateagivennumberofparticlesofagiventype.Alltheseparticlesaregeneratedatonce.Forthenumberyoucanalsouseanegativevalue.Anegativevaluexmeansthataparticleiscreatedwithchance-1/x.Soforexample,ifyouwanttogenerateaparticlewithachanceof25percent,useavalueof-4.

StreamfromEmitterWiththisactionyoutellaparticularemittertostreamagivennumberofparticlesofagiventype.Ineachstepthisnumberofparticlesisgenerated,leadingtoacontinuousstreamofparticles.Theemitterwillcontinuestreamingparticlesuntilyoudestroyitortellittostream0particles.Forthenumberyoucanalsouseanegativevalue.Anegativevaluexmeansthatineachstepaparticleiscreatedwithchance-1/x.Soforexample,ifyouwanttogenerateaparticleaboutevery4steps,useavalueof-4.

Page 132: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Extraactions

OntheExtratabtherealsoareanumberofactionsrelatedtotheplayingofCDs.TheseactionsareonlyavailableintheProEditionofGameMaker.

PlayCDWiththisactionyoucanplaysometracksfromaCDinthedefaultCD-drive.Youspecifythestartingtrackandthefinaltrack.

StopCDStopsthecurrentlyplayingCD.

PauseCDPausesthecurrentlyplayingCD.

ResumeCDResumesapausedCD.

CheckCDIfthereisaCDinthedefaultdrivethenthenextactionisexecuted.

CheckCDPlayingIfaCDisplayinginthedefaultdrivethenthenextactionisexecuted.

Finally,thereareanadditionalactionthatcanbeusefulincertaingames.

SetCursorYoucanusethisactiontoreplacethewindowsmousecursorbyasprite.Youspecifythespriteandwhetherthewindowsmousecursorshouldstillbeshown.Thespritecanbeanimated.Notethatthespritewillonlybeshownintheroom,notintheareaoutsideit.

Page 133: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 134: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Constants

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Inadvancedmodeyoucandefineconstantsthatyoucanuseinscriptsandinvaluesforactions.Eachconstanthasanameandavalue.Namesshouldfollowthesamerulesasvariables,thatis,theymuststartwithaletterorunderscoresymbolandfurtherconsistofletters,digitsorunderscoresymbols.Youarethoughstronglyrecommendedtomakeallyourconstantseasilydistinguishable.Ausualconventionistouseonlycapitallettersandunderscores.

TodefineconstantsyouchoseDefineConstantsfromtheResourcesmenu.Thefollowingformwillshow(inwhichalreadysomeconstantshavebeendefined):

Atthetopyouseetheconstants.Attheleftthereisthenameandattherightthevalue.Youcanselectthenameorvaluewiththemouseandchangeitbytyping.Avalueofaconstantshouldbeaconstantexpression.Thatis,itiseitheraconstantnumberorastring(withquotesaroundit)oritisanexpression.Theexpressionisevaluatedbefore

Page 135: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

anythingelsehappensinthegame.Soitforexamplecannotreferencethecurrentroom,instances,orscripts.Butitcancontainthebuilt-inconstantsandthenamesofresources.

YoucanappendaconstantattheendofthelistusingthebuttonAdd(orbypressingEnter)anddeleteitusingDelete.Youcanalsoinsertaconstantabovethecurrentselectedconstant.Therearealsobuttonstoclearallconstants,tomovethemupordowninthelist,andtosortthembyname.

Finallyyoucansaveallconstantstoatextfileorloadthemfromatextfile.Thisisusefulwhenyouwanttostorecollectionsofusefulconstantsforlateruse.Whenloadingconstantstheyareappendedtothecurrentlist.Thetextfilecanalsobeeditorusingatexteditor.EachlinecontainsaconstantdefinitionoftheformNAME=VALUE.

Itisgoodpractisetoputanyvaluethatyouusemultipletimesinaconstant.Also,ifyouarenotcompletelysureaboutacertainvalueyoubetterputitinaconstantasitisaloteasiertochangetheconstantsthantofindthevaluesinthescriptsandactionsandchangethemthere.

Page 136: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Triggerevents

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Inadvancedmodeanewtypeofeventsisavailable:triggerevents.Triggereventsyoucandefineyourself.Youspecifytheconditionwhentheeventmustbeexecuted.TodefinetriggereventsyouchoseDefineTriggersfromtheResourcesmenu.Thefollowingformwillshow(inwhichalreadysometriggershavebeendefined):

Attheleftyouseealistofalltriggersthathavebeendefined.Initiallythislistisempty.Belowtherearesomebuttonswiththefollowingfunction:

Add.Usethisbuttontoaddanewtriggereventtothelist.Delete.Deletesthecurrentlyselectedtriggereventtothelist.Becarefultoneverdeleteatriggereventthatisusedinanobject.Itmightleadtounexpectedresults.Load.Loadsacollectionoftriggersfromafile.Suchafilemusthaveextension.gmtrg.Thetriggersfromthefileareaddedtothelistoftriggers.Save.Savesthecollectionoftriggerstoafile.Suchafilemusthaveextension.gmtrg.Inthiswayyoucancreateyourowncollectionsof

Page 137: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

usefultriggersthatyoucanuseindifferentgames.Clear.Clearsthelistoftriggers.Becarefultoonlyusethiswhennoobjectusesanytriggerevent.

OnceyouarefinishedyoucanpresstheOKbuttontosavethechanges.Ifyoudonotwanttosavethechanges,closetheformwiththecrossinthetoprightcornerandindicatethatyoudonotwanttosavechanges.

Definingatrigger

Onceyouaddedatriggeryoushouldfillinitsproperties.Firstofallyoumustgivethetriggeraname.Thisnamewillappearinthemenuwithavailabletriggersandintheeventlistsforobjects.Nextyoumustspecifytheconditionthatwilltriggertheevent.ThisisapieceofGML-code.Itmustcontainareturnstatementthatreturnsatrueorfalsevalue.Thetriggerwillfirewhenthereturnvalueistrue.Herearesomeexamples.

AssumeyouwanttocreateaneventthathappenswhentheplayerpressesboththeControlkeyandtheAkey.Forthisyoucanusethefollowingcondition:

{

returnkeyboard_check(ord('A'))&&

keyboard_check(vk_control);

}

Youcanputcompletescriptsintheconditionaslongastheresomewhereisareturnstatement.Forexample,tohaveaneventthathappenwhenthenumberofballsisbetween3and5,youcanusethefollowingcondition:

{

varn;

n=instance_number(obj_ball);

return(n>=3)&&(n<=5);

}

Youcancreatemanyothertypeoftriggerevents.Forexampleevents

Page 138: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

thatcheckforcombinationsofkeysandmousebuttons,eventsthatcheckwhetheryouareneartoanenemy,eventstocheckwhetheryoucollectedenoughmoneyorscore,etc.

Iftheconditiongetsabitlongyoumightwanttoedititinthecodeeditorinstead.TothatendpressthebuttonUsecodeeditor.

Afteryouspecifiedtheconditionyoushouldspecifywhentheconditionistested.Therearethreeoptionshere.Youcantesttheconditionatthebeginningofastep(justbeforethebeginstepevent),inthemiddle(justbeforethenormalstepevent)orattheend(justbeforetheendstepevent).Mostofthetimethedefaultmiddlepositionisfinebutincertaincasesyouneedtheothermoments.

Finally,whenyoualsowanttocalltheeventfromcodeyoucanspecifyaconstantwithwhichyoucanreferincodetotheevent.SeeChapter4formoredetailsaboutcallingeventsfromcode.

Usingatrigger

Onceyouhavedefinedyourscriptsyoucanusethemwhendefiningobjects.WhensettingtheobjectpropertiesandclickonAddEvent,youcannowselectTriggerevents.

Inthedrop-downmenuthatappearsyoucanselectthetypeoftriggereventyouwanttouse.Nowyoucanaddactionstothiseventinthesamewayasyouaddactionstootherevents.

Page 139: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 140: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Includingfilesinstand-alonegames

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Ashasbeenindicatedbefore,youcancreatestand-aloneversionsofyourgame.Sometimesyourgamewilluseadditionalfiles.Forexampleyoumightwanttoincludevideofilesortextfilesthatareusedinthegame.InsomecasesyouwanttoaddDLLsorimagesandsoundsthatareloadedduringtherunningofthegame.Youcanprovidethesetogetherwiththestand-aloneexecutablebutitissometimeseasiertoincludetheminthefile.Inthiswayonlyonefileneedstobedistributed.Includedfileswilldefaultbeexportedwhenthegamestarts.

YoucanindicatethefilesyouwanttoincludeintheexecutableinbychoosingIncludedFilesfromtheResourcesmenu.Thefollowingformwillbeshown:

Atthetopoftheformisalistoffilestoinclude.UseAddtoaddanewfiletothelist,Changetochangeaselectedfile,Deletetodeletetheselectedfile,andCleartoclearthecompletelist.Whenaddingorchanginganentry,thefollowingformwillpopup:

Page 141: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Hereyoucanindicateanumberofproperties.YoucanpresstheLoadbuttontoindicatewhichfilemustbeincluded.YoucanchangetheFileNameifyouwanttosavethefileunderadifferentnamethantheoriginalfilename.

Thereareanumberofoptionsyoucanset.WhenyoucheckStoreintheeditablegmkfiletheincludedfileinnotonlyaddedtotheexecutablebutalsototheeditableversionofthegame.Theadvantageisthatyoucane.g.sendtheeditableversiontosomebodyelseandcanbesurethefileisstillthere.Also,youcanremovetheincludedfileifyouwantormoveitelsewherewithoutproblems.Thedisadvantageisthattheeditableversionofthegamebecomeslargerandtakeslongertoload.

CheckingtheoptionFreememoryafterexportmeansthatafterthefilehasbeenexported(whenrunningthegame)itwillberemovedfrommemory.Ifyouwanttobeabletoexportitagainlateryoushoulduncheckthisoption.Ifafilethatisexportedalreadyexistsitisnormallynotwritten.YoucanchangethisbehaviorbycheckingOverwriteexistingfiles.Also,whenthegameisfinishedthefilesarenormallynotremoved(unlesstheyareinthetemporaryfolderwhichiscompletelyremoved).YoucanchangethisbycheckingRemoveatgameend.

Awordofwarningisinplacehere.Ifyouaretestingyourgame,theworkingdirectoryofthegameisthedirectorywherethe.gmkfileis

Page 142: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

stored.Ifyourincludefilesarealsostoredhereandyouchoosetoremovethemattheendofthegameyoumightloosethemalltogether!Sobetternotstorethesefileswiththe.gmkfilebute.g.inasubfolder!

Finallyyoucanindicatetowhatfolderthefilesareexported.Therearefouroptionshere.Inthedefaultsituationthefilesareexportedinthefolderwherethestand-alonegameisstored.Thisisalsotheworkingdirectoryforthegame.Sothegamecanjustusethefilenamestoaccessthem(nopathsarerequired).Thisworkswellifthestand-aloneisstorede.g.ontheharddiskbutwillfailifitisstoredonaread-onlydevice,e.g.onaCD.

Thesecondpossibilityistoindicatethatthefilesmustbeexportedintothetemporaryfolderthatiscreatedduringtherunningofthegame.Ifyouselectthisoptionyouwillneedtoprovidethepathtothetemporaryfolderwhenyouusethefilenameduringthegame.Thispathcanbeobtainedusingthebuilt-invariabletemp_directory.Don'tforgettoaddthebackslashinthiscase.Sotoe.g.playavideofileyoumighttypeinthefollowingpieceofcode:

{

splash_show_video(temp_directory+'\movie.avi',true);

}

Realizethatthistemporaryfolderisremovedoncethegameisfinished.Soyoue.g.cannotstoresavegamesorspecialinformationinthiscase.OnlychoosethisoptionwhenyouwantthegametoberunfromaCDorwhenyoudonotwriteanyfilesfromwithinyourgame.

Thethirdoptionistoindicatethefoldertowhichthefilemustbeexportedyourself.Ifitdoesnotexistitwillbecreated.E.g.youcouldspecifyC:\MyGame.(Notethatyouneedtoprovideafullpatghandthatyoushouldnotincludeabackslashattheend.)Thisisonlyallowedwhenthegamedoesnotruninsecuremode.

Finally,youcanindicatenottheexportthefileautomatically.Inthiscaseyoushouldusee.g.thefunctionexport_include_file(fname)toexportit

Page 143: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

yourselfwhenrequired.

Page 144: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Moreaboutrooms

RoomsinGameMakerhavemanyoptions.Beforeweonlytreatedthemostimportantones.Inthischapterwewilldiscusstheotheroptions.Whenyouopentheroomforminadvancedmodeitlooksasfollows:

Asyouwillsee,somenewbuttonshavebeenaddedtothetoolbar.Therearebuttonstosorttheinstanceshorizontallyorvertically.Thisisusefulwheninstancepartiallyoverlap.(Whenaddingtilesthesebuttonsandtheothersworkonthetilesratherthantheinstances.)Alsotherearebuttonstolockallinstancesorunlockallinstances.Lockedinstancescannotbemovedordeleted.Thisprotectsyouagainstincidentallyremovinginstances.(However,whenusingthetoolbarbuttonstodeleteorshiftallinstances,alsothelockedonesaredeletedorshifted.)Usingtherightmousebuttonmenu(hold<Ctrl>andrightclickonaninstance)youcanalsolockorunlockindividualinstances.

Finally,youcanindicatethatyouwanttouseanisometricgrid.Thisisveryusefulwhencreatingisometricgames.Firstofall,thegridlinesnowrundiagonally.Alsothesnappingofinstancesisdifferent.(Itworksbest

Page 145: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

whentheoriginoftheinstanceisatthetopleftcornerasisdefault.)

Alsotherearetwonewtabswhichwewilldiscussbelow.

Informationonthedifferentadvancedroomoptionscanbefoundinthefollowingpages:

AdvancedsettingsAddingtilesViews

Page 146: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Advancedsettings

Thereweretwoaspectsinthesettingstabthatwehavenotyetdiscussed.Firstofall,thereisacheckboxlabeledPersistent.Normally,whenyouleavearoomandreturntothesameroomlater,theroomisresettoitsinitialsettings.ThisisfineifyouhaveanumberoflevelsinyourgamebutitisnormallynotwhatyouwantinforexampleanRPG.Heretheroomshouldbethewayyouleftitthelasttime.CheckingtheboxlabeledPersistentwilldoexactlythat.Theroomstatuswillberememberedandwhenyoureturntoitlater,itwillbeexactlythesameasyouleftit.Onlywhenyourestartthegamewilltheroombereset.Actually,thereisoneexceptiontothis.Ifyoumarkedcertainobjectsasbeingpersistent,instancesofthisobjectwillnotstayintheroombutmovetothenextroom.

Secondly,thereisabuttonlabeledCreationcode.HereyoucantypeinapieceofcodeinGML(seelater)thatisexecutedwhentheroomiscreated.Thisisusefultofillincertainvariablesfortheroom,createcertaininstances,etc.Itisimportanttounderstandwhatexactlyhappenswhenyoumovetoaparticularroominthegame.

First,inthecurrentroom(ifany)allinstancesgetaroom-endevent.Nextthenon-persistentinstancesareremoved(nodestroyeventisgenerated!).Next,forthenewroomthepersistentinstancesfromthepreviousroomareadded.Allnewinstancesarecreatedandtheircreationeventsareexecuted(iftheroomisnotpersistentorhasnotbeenvisitedbefore).Whenthisisthefirstroom,forallinstancesthegame-starteventisgenerated.Nowtheroomcreationcodeisexecuted.Finally,allinstancesgetaroom-startevent.

So,forexample,theroom-starteventscanusevariablessetbythecreationcodefortheroomandinthecreationcodeyoucanrefertotheinstances(bothnewonesandpersistentones)intheroom.

Page 147: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thereisonefurtheroption.Inthepop-upmenuwhenyourightclickonaninstancewiththe<Ctrl>keyyoucannowindicatesomecreationcodeforthespecificinstance.Thiscodeisexecutedwhentheroomisstarted,justbeforethecreationeventoftheinstanceisexecuted.Thisisveryusefultoe.g.setcertainparametersthatarespecifictotheinstance.

Page 148: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Addingtiles

Youcanalsocreateso-calledtiledbackground.Theideabehindthisisasfollows:Inmanygamesyouwillwanttohavenicelookingbackgrounds.Forexample,inamazegame,thewallsofthemazeshouldnicelymatchup,andinplatformgamesyouliketoseebeautifullydrawnplatforms,trees,etc.YoucandothisinGameMakerbydefiningmanydifferentobjectsandcomposingyourroomsfromtheseobjects.Theproblemthoughisthatthistakesalotofwork,useslargeamountsofresources,andmakesthegamesrunslowlybecauseofthemanydifferentobjects.Forexample,tocreatenicewallsinmazegamesyouneedasastart15differentlyshapedwallobjects.

Thestandardwayout,usedinmanygames,isthatthewallsandotherstaticobjectsareactuallydrawnonthebackground.But,youmightask,howdoesthegameknowthatanobjecthitsawallifitisdrawnonthebackgroundonly?Thetrickisasfollows:Youcreatejustonewallobjectinyourgame.Itmusthavetherightsizebutitdoesnotneedtolooknice.Whencreatingtheroom,placethisobjectatallplaceswherethereisawall.And,herecomesthetrick,wemakethisobjectinvisible.Sowhenplayingthegameyoudon'tseethewallobjects.Youseethebeautifulbackgroundinstead.Butthesolidwallobjectsarestillthereandtheinstancesinthegamewillreacttothem.

Youcanusethistechniqueforanyobjectthatisnotchangingitsshapeorposition.(Youcannotuseitwhentheobjectmustbeanimated.)Forplatformgames,youprobablyneedjustonefloorandonewallobject,butyoucanmakebeautifullylookingbackgroundswhereitlooksasifyouwalkongrass,ontreebranches,etc.

Toaddtilestoyourroomyoufirstneedtoaddabackgroundresourcetoyourgamethatcontainsthetiles.Ifyouwanttohaveyourtilespartiallytransparent,makesureyoumakethebackgroundimagetransparentwhenloadingit.Whenaddingthebackgroundresourceindicatethatitmustbeusedasatileset.Nextindicatethesizeofeachtileandwhetherthereisroombetweenthetiles,aswasindicatedinthechapteron

Page 149: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

backgroundresources.

Now,whendefiningyourroom,clickonthetabtiles.Thefollowingformisshown(actually,wealreadyaddedsometilesinthisroomandswitchedoffthegrid).

Atthelefttopthereisthecurrentsetoftilesused.Toselecttheset,clickonthemenubuttonbelowitandselecttheappropriatebackgroundimage.

Nowyoucanaddtilesbyselectingthetileyouwantatthetopleft,andnextclickingattheappropriateplaceintheroomattheright.Thisworksinexactlythesamewayasforaddinginstances.Underlyingtilesareremoved,unlessyouunchecktheboxDeleteunderlying.Youcanusetherightbuttontodeletetiles.Holdthe<Shift>keytoaddmultipletiles.Andholdthe<Ctrl>keytomovetilestoanewplace.The<Alt>keywillavoidsnappingtothegird.Alsothereisagainapop-upmenuwhenyouholdthe<Ctrl>keyandclickonatilewiththerightmousebutton.Thebuttonsinthetoolbarwillnowclearalltiles,shiftalltiles,sortthetilesorlock/unlockthem.(Actuallytheyonlyoperateonthecurrentlayer;seebelow.)

Insomesituationsyoumightwanttoputapartofthebackgroundinthe

Page 150: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

roomthatisnotexactlythesizeofatileorconsistsofmultipletiles.Thiscanbedoneasfollows.Inthetop-leftimagepresstheleftmousebuttonwhileholdingthe<Alt>key.Nowyoucandraganareawhichyoucanthenplaceintheroominthesamewayastiles.Toselectmultipletiles,holdthe<Shift>key.Notethatthisonlyworkscorrectlywhenthereisnoseparationbetweenthetiles.Ifyouwanttoselectanareathatismultipleoftheroomgridsize,holdthe<Ctrl>keyratherthanthe<Shift>key.(Notethatyoucanactuallychangethekeyyouholdduringthedragging.Thiscansometimesbeuseful.)

Tilescanbeplacedinlayersatdifferentdepths.Atthebottomyouseethecurrentdepth.Defaultthisis1000000whichisnormallybehindallinstances.Sotheinstanceswillmoveinfrontofthetiles.YoucanusetheAddbuttontoaddnewtilelayers,eachwithadifferentdepth.Negativedepthscanbeusedtoputtilesinfrontofinstances.Ifyoualsogiveobjectsdifferentdepthsyoucanputthembetweendifferenttilelayers.IfyoupressDeleteyoudeleteatilelayertogetherwithallitstiles.(Theremustalwaysbeatleastonelayer.)IfyoupressChangeyoucanchangethedepthofatilelayer.Ifyougiveitthesamedepthasanotherlayer,thelayersaremerged.

Usingtilesisapowerfulfeaturethatshouldbeusedasmuchaspossible.Itismuchfasterthanusingobjectsandthetileimagesarestoredonlyonce.Soyoucanuselargetiledroomswithverylittlememoryconsumption.

Page 151: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Views

Finally,thereisatablabeledviews.Thisgivesamechanismfordrawingdifferentpartsofyourroomatdifferentplacesonthescreen.Therearemanyusesforviews.Firstofall,inanumberofgamesyouwanttoshowonlypartoftheroomatanytime.Forexample,inmostplatformgames,theviewfollowsthemaincharacter.Intwo-playergamesyouoftenwantasplit-screenmodeinwhichinonepartofthescreenyouseeoneplayerandinanotherpartyouseetheotherplayer.Athirduseisingamesinwhichpartoftheroomshouldscroll(e.g.withthemaincharacter)whileanotherpartisfixed(forexamplesomestatuspanel).ThiscanallbeeasilyachievedinGameMaker.

Whenyouclickthetablabeledviewsthefollowinginformationwillshow:

AtthetopthereisaboxlabeledEnabletheuseofViews.Youmustcheckthisboxtouseviews.Belowthisyouseethelistofatmosteightviewsyoucandefine.Belowthelistyoucangiveinformationfortheviews.Firstofallyoumustindicatewhethertheviewshouldbevisiblewhentheroomstarts.Makesureatleastoneviewisvisible.Visibleviewsareshowninbold.

Page 152: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Aviewisdefinedbyarectangularareaintheroom.Thisistheareathatmustbeshownintheview.Youspecifythepositionofthetop-leftcornerandthewidthandheightofthisarea.Secondly,youmustspecifywherethisareaisshowninthewindowonthescreen.Thisiscalledthe(view)port.Againyouspecifythepositionofthetop-leftcornerandthesize.Ifyouhaveasingleviewthepositionistypically(0,0).Notethatthesizeoftheportcanbedifferentfromthesizeoftheview.Inthiscasetheviewwillbescaledtofitintheport.(Incodeitisalsopossibletorotateaview.)Theportscanoverlap.Inthiscasethearedrawnintheindicatedorderontopofeachother.

Asindicatedabove,youoftenwanttheviewtofollowacertainobject.Thisobjectyoucanindicateatthebottom.Iftherearemultipleinstancesofthisobject,onlythefirstoneisfollowedbytheview.(Incodeyoucanalsoindicatethataparticularinstancemustbefollowed.)Normallythecharactershouldbeabletowalkaroundabitwithouttheviewchanging.Onlywhenthecharactergetsclosetotheboundaryoftheview,shouldtheviewchange.Youcanspecifythesizeoftheborderthatmustremainvisiblearoundtheobject.Finally,youcanrestrictthespeedwithwhichtheviewchanges.Thismightmeanthatthecharactercanwalkoffthescreen,butitgivesamuchsmoothergameplay.Use-1ifyouwanttheviewtochangeinstantaneously.

Page 153: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Fonts

WhenyouwanttodrawtextinyourgamethistextisdrawninanArial12pointsfont.Tomakemorefancylookingtextsyouprobablywanttousedifferentfonts.Tousedifferentfontsyoumustcreatefontresources.Ineachfontresourceyouspecifyaparticulartypeoffontwhichcanthenbeusedinyourgameusingtheactiontosetafont.

Tocreateafontresourceinyourgame,usetheitemCreateFontintheResourcesmenuorusethecorrespondingbuttononthetoolbar.Thefollowingformwillpopup.

Asalwaysyoushouldgiveyourfontresourceaname.Nextyoucanpickthenameofthefont.Alsoyoucanindicateitssizeandwhetheritshouldbeboldand/oritalic.Realizethatlargefontstakealotofmemorytostore.Soyouarestronglyrecommendednottousefontswithasizelargerthansay32.(Itispossibletoscalethefontswhilerunningthegame.)Anexampleoftheindicatedfontisshownatthebottom.

Afonttypicallyconsistof256characters,numberedfrom0to255.Butingeneralyouuseonlyasmallportionofthese.Sodefaultinafontonlythecharactersfrom32till127arestoredinthefont.Themorecharacters

Page 154: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

youstoreinthefontthemorememoryitwilluse.Youcanchangethecharacterrangeused.ToseetheindexofeachcharacteryoucanusetheCharacterMapthatcanbefoundintheWindowsStartmenuunderAccessories/SystemTools.Somestandardrangescanbeindicatedusingthebuttons:TheNormalrangefrom32till127,theAllrangefrom0till255,theDigitsrangethatonlycontainsthe10digits,andtheLettersrangethatcontainsalluppercaseandlowercaseletters.Otherrangescanbeusedbytypinginthefirstandlastcharacterindex.Ifacharacterdoesnotlieintherangeitisreplacedbyaspace.

Normallyyouhavealargenumberofdifferentfontsinstalledonyourcomputerandtherearewebsiteswhereyoucandownloadhundredsmore.Theproblemisthatifyouusetheminyourgameandthengiveyourgametosomebodyelsetoplaythereisabigchancethattheotherpersondoesnothavethesamefontsinstalledonhisorhercomputer.Toavoidthis,GameMakerembedsallthefontsyouwanttouseinthegamefile,butonlyinthestand-alonegames.Soifyougiveastand-alonegametosomeoneelseyoudon'tneedtoprovidethefontfiles.Butifyougivesomebodytheeditableversionofyourgameandyouusefancyfonts,youbetteralsoprovidethepersonwiththecorrectfontfiles.

Page 155: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Paths

Inmoreadvancedgamesyouoftenwanttoletinstancesfollowcertainpaths.Eventhoughyoucanindicatethisbye.g.usingtimereventsorcode,thisisrathercomplicated.Pathresourcesareaneasiermechanismforthis.Theideaisrathersimple.Youdefineapathbydrawingit.Nextyoucanplaceanactioninthecreationeventoftheobjecttotelltheobjecttofollowtheparticularpath.Thischapterwillexplainthisindetail.

Definingpaths

Tocreateapathinyourgame,chooseCreatePathfromtheResourcesmenu.Thefollowingformwillpopup(intheexamplewealreadyaddedalittlepath).

Atthetopleftoftheformyoucansetthenameofthepath,asusual.Belowityoufindthepointsthatdefinethepath.Eachpointhasbothapositionandaspeed(indicatedwithsp).Dependingonhowyouusethepath,thepositioniseitherabsolute,thatis,theinstanceforwhichyouwill

Page 156: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

laterusethepathwillfollowitatthatparticularplace,oritisrelative,thatis,theinstancewillalwaysstartatthefirstpositiononthepathandfollowthepathfromthere.Thespeedshouldbeinterpretedasfollows.Avalueof100meanstheoriginalspeedgivenforthepathwhenassigningittotheinstance.Alowervaluereducesthespeed,ahighervalueincreasesit(soitindicatesthepercentageoftheactualspeed).Speedwillbeinterpolatedbetweenpoints,sothespeedchangesgradually.

ToaddapointpressthebuttonAdd.Acopyismadeofthecurrentlyselectedpoint.Nowyoucanchangetheactualpositionandspeedbychangingthevaluesintheeditboxes.Wheneveryouselectapointinthelist,youcanalsochangeitsvalues.PressInserttoinsertanewpointbeforethecurrentone,andDeletetodeletethecurrentpoint.

Attherightoftheformyouwillseetheactualpath.Thereddotindicatesthecurrentlyselectedcontrolpoint.Thebluedotsaretheothercontrolpoints.Thegreensquareindicatesthepositionwherethepathstarts.Youcanalsochangethepathusingthemouse.Clickanywhereontheimagetoaddapoint.Clickonanexistingpointanddragittochangeitsposition.Whenyouhold<Shift>whileclickingonapoint,youinsertapoint.Finally,youcanusetherightmousebuttontoremovepoints.(Notethatyoucannotchangethespeedthisway.)Normallythepointswillbealignedwithagrid.Youcanchangethegridsettingsatthetoptoolbar.Hereyoucanalsoindicatewhetherthegridshouldbevisibleornot.Ifyouwanttopreciselypositionapoint,holdthe<Alt>keywhileaddingormovingit.

Youcaninfluencetheshapeofthepathintwoways.Fistofallyoucanusethetypeofconnection.Youcaneitherchoosestraightlineconnectionsorasmoothpath.Secondly,youcanindicatewhetherthepathmustbeclosedornot.

Onthetoolbarthereareanumberofimportantcontrols.Fromlefttorighttheyhavethefollowingmeaning.Thefirstbuttonindicatesthatyouarereadyandwanttoclosetheform,keepingthechanges.(Ifyouwanttodiscardthechanges,pressthecrosstoclosethewindowandindicatethatyoudonotwanttosavethechanges.)Nextthereisthebuttontoundothelastchange.

Page 157: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thefollowingsetoftoolbarbuttonsallowsyoutheclearthepath,reversetheorderinwhichthepathistraversed,shiftthepath,mirrorithorizontally,flipitvertically,rotateit,andscaleit.Nexttherearebuttonstoshifttheview(notthepathitself;theactualviewareaisindicatedinthestatusbaratthebottom)andtocentertheview.

Asalreadyindicatedaboveyoucannextsetthesnapvaluesandwhethertoshowthegrid.Finallythereisabuttontoindicatethatyouwanttoseeaparticularroomasbackgroundforthepath.Usingthisyoucaneasilyputthepathataparticularplaceintheroom,forexampleonaracetrack,sothatlatertheinstanceswillfollowthecorrectroute.(Thisonlymakessensewhenyouuseabsolutepaths;seebelow.)

Assigningpathstoobjects

Toassignapathtoaninstanceofanobject,youcanplacethepathactioninsomeevent,forexampleinthecreationevent.Inthisactionyoumustspecifythepathfromthedropdownmenu.Therearesomefurthervaluesyoucanprovide.

Youmustindicatethepaththatmustbefollowedandthespeedinpixelsperstep.Whenthespeedispositivetheinstancestartsatthebeginningofthepath.Ifitisnegativeitstartsattheend.Rememberthatwhenyoudefinedthepathyouspecifytheactualspeedrelativetothisindicatedspeed.Thereisalsoanactiontochangethespeedwithwhichthepathisexecuted.Youcould,forexample,usethistoletaninstanceslowdownorspeedupalongitspath.Notethatthenormalspeedoftheinstanceisignored(actuallysetto0)whenexecutingapath.Alsothingslikegravityandfrictiondonotinfluencethemotionalongapath.

Nextyouspecifytheendbehavior,thatis,whatshouldhappenwhentheendofthepathisreached.Youcanchoosetostopthemotionandendthepath.Youcanalsorestartthepathfromthebeginning,thatis,theinstancejumpsbacktothepositionwherethepathwasstartedandexecutesthepathagain.Athirdoptionistorestartfromthecurrentposition,thatis,theinstancefollowsthepathagainbutnowwiththisnewstartingposition(thisisthesamewhenthepathisclosed).Finallyyou

Page 158: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

canchoosetoreversethemotion,makingtheinstancegobackandforthalongthepath.Notethatalsoattheendofthepathaneventhappens;seebelow.

Finallyyoucanindicatewhetherthepathmustbeabsoluteorrelative.Anabsolutepathisexecutedattheplacewhereitisdefined.Theinstanceisplacedatthestartpositionandmovedfromthere(endpositionwhenspeedisnegative).Thisis,forexample,usefulwhenyouhavearacetrackonwhichyouhavedefinedthepath.Whenyouchooserelativetheinstancesstartsexecutingthepathfromitscurrentposition.Thisisusefulwhenaninstanceshouldmakealocalmotion.Forexample,spaceshipsinaspaceinvadergamecanmakeaparticularturnfromtheircurrentposition.

Whenyouwanttoplacetheinstanceatadifferentpointalongitspathyoucanusetheactiontosetthepathposition.Apathpositionalwaysliesbetween0and1,0indicatingthestartpositionand1theendpositiononthepath.Notethatineachstepthedirectionvariableisautomaticallysettothecorrectdirectionalongthepath.Youcanusethisvariabletochoosethecorrectorientationforthesprite.

Whenusingscriptsorpiecesofcodeyouhavemorecontroloverthewaythepathisexecuted.Thereisafunctiontostartapathforaninstance.Thevariablepath_positionindicatesthecurrentpositiononthepath(between0and1asindicatedabove).Thevariablepath_speedindicatesthespeedalongthepath.Avariablepath_scalecanbeusedtoscalethepath.Avalueof1istheoriginalsize.Alargervalueindicatesthatthepathismadelarger;asmallervaluemakesitsmaller.Thevariablepath_orientationindicatestheorientationinwhichthepathisexecuted(indegreescounter-clockwise).Thisenablesyoutoexecutethepathinadifferentorientation(e.g.movingupanddownratherthanleftandright).Thereisalsoavariabletocontroltheendbehavior.Finallytherearelotsoffunctionstoaskforpropertiesofpaths(e.g.thexandycoordinateatacertainpositions)andtherearefunctionstocreatepaths.Thereareevenfunctionsthatcreatecollisionfreepathsforaninstancetoreachacertaingoal.SeethelatersectionsonGMLfordetailsonthis.

Youmightwonderwhathappenswhentheinstancecollideswithanother

Page 159: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

instancewhileitfollowsapath.Basicallythesamehappensaswhentheinstancemoveswithaspeed.Whenthereisasolidinstance,theinstanceisplacedbackatitspreviouslocation.WhenbothinstancesarenotsolidtheyareplacedattheirnewpositionsNextthecollisionevent(s)areexecutedanditischeckedwhetherthecollisionhasbeenresolved.Ifnotandtheotherinstanceissolidtheinstancewillstop,asitshould(assumingthereisacollisioneventdefined).Also,thepath_positionvariableisnotincreased.Whentheblockinginstancedisappearstheinstancewillcontinuetofollowitspath.Tohandlecollisionsyourselfthevariablepath_positionpreviouscanbeuseful.Itholdsthepreviouspositionforthepathandyoucansetthepathpositiontothisvariabletoavoidadvancingalongthepath.

Thepathevent

Asdescribedabove,youcanindicatewhatmusthappenwhentheinstancereachestheendofthepath.AtthismomentalsoanEndofPatheventoccurs.YoucanfinditundertheOtherevents.Hereyoucanplaceactions.Forexample,youmightwanttodestroytheinstance,orletitstartanew(different)path.

Page 160: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Timelines

Inmanygamescertainthingsmusthappenatcertainmomentsintime.Youcantrytoachievethisbyusingalarmeventsbutwhenthingsgettoocomplicatedthiswon'tworkanymore.Thetimelineresourceismeantforthis.Inatimelineyouspecifywhichactionsmusthappenatcertainmomentsintime.Youcanusealltheactionsthatarealsoavailableforthedifferentevents.Onceyoucreateatimelineyoucanassignittoaninstanceofanobject.Thisinstancewillthenexecutetheactionsattheindicatedmomentsoftime.Letusexplainthiswithanexample.Assumeyouwanttomakeaguard.Thisguardshouldmove20timestepstotheleft,then10upwards,20totheright,10downwardsandthenstop.Toachievethisyoumakeatimelinewhereyoustartwithsettingamotiontotheleft.Atmoment20yousetamotionupward,atmoment30amotiontotheright,atmoment50amotiondownwardsandatmoment60youstopthemotion.Nowyoucanassignthistimelinetotheguardandtheguardwilldoexactlywhatyouplanned.Youcanalsouseatimelinetocontrolyourgamemoreglobally.Createaninvisiblecontrollerobject,createatimelinethatatcertainmomentscreatesenemies,andassignittothecontrollerobject.Ifyoustarttoworkwithityouwillfindoutitisaverypowerfulconcept.

Tocreateatimeline,chooseCreateTimeLinefromtheResourcesmenu.Thefollowingformwillpopup.

Page 161: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Itlooksabitliketheobjectpropertiesform.Attheleftyoucansetthenameandtherearebuttonstoaddandmodifymomentsinthetimeline.Nextthereisthelistofmoments.Thislistspecifiesthemomentsintimestepsatwhichassignedaction(s)willhappen.Thenthereisthefamiliarlistofactionsfortheselectedmomentandfinallythereisthetotalsetofactionsavailable.Attheleftyoucanusethefollowingbuttons:

Add.Usethistoaddamomenttothetimeline.Youmustindicatethemoment,whichisthenumberofstepssincethetimelinewasstarted.Nowyoucandragactionstothelistasforobjectevents.Change.Usethisbuttontochangethetimestepsforthecurrentlyselectedmoment.Delete.Usethisbuttontodeleteamomentorarangeofmoments.Youmustindicatethetimestepofthefirstmomenttodeleteandthelastone.Allmomentsinbetweenwillbedeleted.Clear.Usethisbuttontocleartheentirelistofmoments.Shift.Usethisbuttontoshiftarangeofmomenttoanewmoment.Youmustindicatethestartoftherange,theendoftherange,andthenewtimesteptowhichthestartoftherangemustbeshifted.Whendifferentmomentsbecomethesametheiractionlistswillbemerged.Duplicate.Thisisalmostthesameastheshiftbuttonbutinthiscaseacopyofthemomentsaremade.Spread.Usethisbuttontospreadoutarangeofmomentsbyaddingtimebetweenthemorputthemclosertogetherbyremovingtime

Page 162: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

betweenthem.Youspecifythestartandtheendoftherangeandthepercentageforthespread.Apercentageof100meansnothingchanges.Forvaluessmallerthan100themomentsaremovedclosertogetherandforvalueslargerthan100theyaremovedfurtherapart.Forexampleifyouhavemomentsattimesteps5,8,and12andyouindicateasrange5:12andapercentage200,themomentswillmovetotimesteps5,11,and19.(Theintervalsbetweenthemhavedoubled.)Whendifferentmomentsbecomethesametheiractionlistswillbemerged.Merge.Usethisbuttontomergeanumberofmomentsintoasingleone.Youspecifythestartandtheendoftherangeandtheywillallbemergedintothestartmoment.

Makesureyoudonotcreatenegativetimemoments.Theywillneverbeexecuted.

ThereisalsoabuttonShowInformationthatshowsthetimelineinareadableform.

Thereareanumberofactionsrelatedtotimelines.YoucanfindtheminthesectiononMoreMainActions.

Page 163: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Scripts

GameMakerhasabuilt-inprogramminglanguagecalledGML.OnceyoubecomemorefamiliarwithGameMakerandwanttouseittoitsfullestextend,itisadvisabletostartlearningtousethislanguage.FormoredetailsintheGMLlanguageseePart4ofthisdocumentation.

Therearetwowaystousethelanguage.Firstofallyoucancreatescripts.Thesearepiecesofcodetowhichyougiveaname.Theyareshownintheresourcetreeandcanbesavedtoafileandloadedfromafile.TheycanevenbeusedtoformalibrarythatextendsthepossibilitiesofGameMaker.Alternatively,youcanaddacodeactiontosomeeventandtypeapieceofcodethere.Addingcodeactionsworksinexactlythesamewayasaddingscriptsexceptfortwodifferences.Codeactionsdon'thaveanameandcannotusearguments.Alsotheyhavethewell-knownfieldtoindicatetowhatobjectstheactionshouldapply.Fortherestyouentercodeinexactlythesamewayasinscripts.WerecommendyoutousescriptsforallbutsimplepiecesofcodeasGameMakerhasmanymorefeaturesthatdealwithscripts.Sowefurtherconcentrateonscriptsinthischapter.

Asstatedbefore,ascriptiswrittenwithcodeinGML(thebuilt-inprogramminglanguage)andismeanttoperformaparticulartask.Scriptscantakesinput-variablescalledarguments(sometimescalledparameters).Toexecuteascriptfromanyevent,youcanusethescriptaction.Inthescriptactionyouspecifythescriptyouwanttoexecute,togetherwiththeuptofivearguments.

Youcanalsoexecuteascriptfromwithinapieceofcode(adifferentscript)inthesamewayyoucallaGM-function.Inthatcaseyoucanuseupto16arguments.Scriptscanreturnavalue.Thisisoftenusedtobuildcalculatingmethods(mathematicalmethods).Thereturnkeywordisusedforthis.Nocodeafterthereturnkeywordisexecuted!Whenascriptreturnsavalue,youcanalsouseitasafunctionwhenprovidingvaluesinotheractions.

Page 164: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ScriptsareextremelyusefultoextendthepossibilitiesofGameMaker.Thisdoesthoughrequirethatyoudesignyourscriptscarefully.Scriptscanbestoredinfilesthatcanbeaddedtoyourgame.Toimportascriptfile,usetheitemImportscriptsfromtheScriptsmenu.TosaveyourscriptsintheformofafileuseExportscripts.Scriptlibrariesaresimpletextfiles(althoughtheyhavetheextension.gml).Preferablydon'teditthemdirectlybecausetheyhaveaspecialstructure.

Tocreateascriptinyourgame,chooseCreateScriptfromtheResourcesmenu.Acodeeditorwillappearthatwillbedescribednext.

Thecodeeditor

Whencreatingoreditingascript(oracodeaction)thefollowingcodeeditorformwillappear(intheexamplewealreadyaddedalittlescriptthatcomputedtheproductofthetwoarguments).

Atthetoprightyoucanindicatethenameofthescript.Youshouldgiveallofyourscriptsasensiblename.Makesurethenameonlyconsistsofletter,digits,andthe_symbol.Itshouldnotstartwithadigit.Inthiswayyoucanusethescriptlaterasafunctionincode.

Atthetopyouhaveatoolbarwithsomeusefulbuttons.Fromlefttoright

Page 165: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

youhavetheOKbuttontoclosetheeditor,savingthechanges,buttonstoloadthescriptfromatextfile,saveittoatextfile,andprintit.

Nextthereareundoandredobuttons.Theeditorwillbasicallyrememberallchangesyoudidandyoucanundothem(orredotheundonechanges).YoucanchangethemaximalnumberofundooperationsinthePreferences.Hereyoucanalsoindicatewhetheryouwanttogrouptheundooperations(suchthate.g.typingalineoftextcanbeundoneinonestep)orthateverykeystrokeisseparatesaved.Youcanuse<Ctrl>+Zforundoand<Ctrl>+<Shift>+Zforredo.

Nexttothistherearebuttonstocut,copy,andpastetext,asyoushouldbefamiliarwith.Thefinaltwobuttonsareforfindingandreplacingandforcodechecking.Thesewillbeexplainedbelowindetail.

Belowthetoolbarthereistheareawhereyoucantypethetext.Atthelefttherearethelinenumbers.(YoucanswitchtheseonandoffusingtheF9key.)Thelinewiththecursoronitismarkedinbold.Thedarkredbarbehindcertainlinenumbersindicatedthattheselineshavechanged.Youwillnoticethatyoucantypetextanywhereonthelines.Soalinedoesnotreallyhaveanend.Thistendstobeusefulwhenalligningtext.Therearemanyeditingpossibilities,thatwillbedescribedbelow.

Atthebottomthereisthestatusbar.Thisshowsfromlefttorightthecurrentlinenumber,totalnumberoflinesandcursorposition.WhetheryouareinInsertmodeorOverwritemode.(InOverwritemodealsothecursorchnangestomakeitclearthatyouareoverwritingtheexistingtext.)Nextthereisthepointsizeforthefontused.YoucanuseF7andF8todecreaseorincreasethefontsize.(YouhavemorecontroloverthefontsizeandtypeinthePreference.)

Editingtools

Theeditorhasmanyeditingpossibilities.Someofthesecanalsobeaccessedthroughthepop-upmenuthatappearswhenyoupresstherightmousebutton.Herearethemostimportantones:

Page 166: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

MultipleundoandredoeitherperkeypressoringroupsThearrowkeysmoveyouaroundinthetext.Use<Ctrl>withtheleftandrightarrowkeytomovetothebeginningofthepreviousornextword.Use<Ctrl>withtheupanddownkeytoalsoscrollthetext.Holdthe<Shift>keytoselecttext.Doubleclickthelinenumbertoselectthecompleteline.TheHomekeymovestothebeginningofthelineandtheEndkeytotheendoftheline.With<Ctrl>theymovetothestartandendofthescript.Holdthe<Shift>keytoselecttext.Youcanscrollthroughthetextwiththemousewheel.With<Ctrl>thecursorscrollswiththetext.Holdthe<Shift>keytoselecttext.Intelligentautoindentthatalignswiththepreviouslinewhenyouusethereturnkeyofthebackspacekey(canbesetinthepreferences).Intelligenttabbingthattabstillthefirstnonspaceinthepreviouslines(canbesetinthepreferences).Use<Ctrl>+Itoindentselectedlinesand<Shift>+<Ctrl>+Itounindentselectedlines.Hold<Ctrl>withtheBackspaceorDeletekeytodeleteuntilthebeginningofthepreviousornextword.Youcandragaselectionwiththemouse.(Use<Ctrl>tocopyit.)Thenewlocationisimmediatelyshown.Cut,copyandpasteoftextbetweenscriptformsandotherprograms.UseF12toopenthescriptorresourcewhosenameisatthecursorposition.

Colorcoding

Asyoumighthavenoticed,partsofthescripttextarecolored.Theeditorknowsaboutexistingobjects,built-invariablesandfunctions,etc.Color-codinghelpsalotinavoidingmistakes.Inparticular,youseeimmediatelyifyoumisspelledsomenameoruseakeywordasavariable.Ifyoudon'tlikethecolorcoding,inthePreferencesyoucanswitchitonandoff(youcanalsouseF10).InthePreferencesyoucanalsochangethecolorforthedifferentcomponentsofthecode.

Page 167: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Functionandvariablehelp

GameMakercontainsmanybuilt-infunctionsandvariablesandyouaddyourownresourcesandscriptstothis.Soitmightbehardtorememberallofthem.Fortunatelytheeditorhelpsyouwiththis.Whenyoutypepartofaname(atleasttwocharacters)andwaitalittle,alistisshownofallpossibilities.Forexample,asfollows:

Youcancontinuetypingandthelistwilladapt.YoucanusetheupanddownkeystoscrollthroughthelistandpressEntertoreplacethetextyouaretypingwiththeselectedfunctionorvariablename.

Youcanswitchthisfeatureonandoffinthepreferences.Youcanalwaysforcethelisttoappearbypressing<Ctrl>+Space.

Asecondformofhelpisgivenwhenyouaretypingintheargumentsforafunction.Inthiscase,inthestatusbaratthebottomthefunctionwithitsargumentsisgiven.Thecurrentargumentyouaretypingisshowninbold.Inthiswayyouwillneverforgetargumentsorgettheorderwrong.

Findandreplace

Itiscommonthatyouwanttofindsomepieceoftextinyourcodeorreplacesometextwithanotherone.TothisendpresstheFindbuttoninthetoolbar.Apanelwillshowupattherightoftheform,asfollows:

Page 168: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Youcantypethefindstringatthetop.Notethatinthecodealloccurrencesofthefindstringareimmediatelyshownwithayellowbackground.(YoucanswitchthisoffinthePreferences.)Asusualyoucanindicatewhetherthesearchmustbecasesensitive(whichisnormallywhatyouwantasvariableandfunctionnamesinGMLarealsocasesensitive)andwhetheryouwanttoonlysearchforwholewords.Notethattheeditorremembersyourmostrecentsearches.

Withthebuttonswiththebluearrowsyoucannowmovetotheprevious,next,first,andlastoccurrenceofthefindstring.Itwillbeselectedinthetextsuchthatyoucane.g.deleteit.

Whenyouwanttoreplaceoccurrences,alsotypeatextinthereplacebox.Nowyoucanusethebuttonstoreplacethepreviousoccurrence,thenext,thefirst,thelast,oralloccurrencesofthefindtext.RememberyoucanalwaysuseUndotoundothereplacements.

Codesnippets

Codesnippetsaresmallpiecesofcodethatyouwilloftenuse.Youcanaddtheminthecodethroughthesnippetmenu.TothisendpressF2.Amenuappearsfromwhichyoucanselectthesnippet.Itwillbeinsertedatthecursorinyourcode.Somepiecesconsistsofcapitallettersonly.

Page 169: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thesemuststillbereplacedbyyou.Thefirstoneisselectedforreplacement.Toreplaceanother,simplydoubleclickonit.

Youcandefineyourowncodesnippetsifyouwant.Thesnippetsarestoredinthefilesnippets.txtinthefolderinwhichGameMakerisinstalled.Youcaneditthisfilewithanytexteditor.Eachsnippetisonaseparatelineandthereshouldbenoblanklines.Itstartswiththenameofthesnippet(showninthemenu)followedbythecolon(:)followedbytheactualsnippet.Use#foranewlineandputthetextthatneedstobeselectedfirstbetween|symbols.Seetheexamplesthatarealreadyinthefile.(Bettermakeabackupofitbeforeyoustartchangingit.)

Errorchecking

Inthetoolbaratthetopthereisabuttonwithwhichyoucanswitcherrorcheckingonoroff.Whenerrorcheckingison,GameMakerconstantlyteststhecodeyouaretypingandreportsthefirsterroritfindsatthebottomofthewindow.Alsothelinenumberforthelinewiththeerrorisdrawninred.Youcanclickontheerrormessagetogotothecorrectlineandpositiontocorrecttheerror.Notethatnotallaspectscanbetestedatthisstagebutthesyntaxofyourscriptwillbetested,togetherwiththeexistenceoffunctionsused.

Whenyoustarttypingascript,errorcheckingmightbeannoyingsoyoucanswitchitoff.Butwhenthescriptisalmostreadyyoubetterswitchitontocorrectalltheerrors.Notethatalsothecolorcodingwillhelpyoucatcherrors.Finally,whenyouputyourcursoratabrackettheeditorwillshowyouthecorrespondingopeningorclosingbracket.Ifitcannotfindit,itisshowninred.(YoucanswitchthisoffinthePreferences.)

Debugging

Whencreatingscriptsyoucaneasilymakemistakes.Alwaystestthescriptsbyusingtheerrorcheckingbutton.However,thiswillnotcatchallerrors.Soyouwillneedtorunthegametotestyourcode.

Page 170: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Whenanerroroccursduringtheexecutionofascriptthisisreported,withanindicationofthetypeoferror,thescriptoractionitoccursin,andthelineandposition.Rarelyyouwillseeapopupwiththetext"Unexpectederroroccurredduringthegame".Thiserrormessageindicatethatsomeproblemoccurredinwindowsorinthehardware.Oftenthereasonforthisisinfiniterecursion,lackofmemoryorinsufficienthardware,driversorfirmware.Generallyspeaking,theseerrorshavetodowithproblemsoutsidetheGameMakerenvironment.

Ifyouneedtocheckthingsmorecarefully,youcanrunthegameindebugmode.Nowaformappearsinwhichyoucanmonitorlotsofinformationinyourgame.

UndertheRunmenuyoucanpausethegame,runitstepbystepandevenrestartit.UndertheWatchmenuyoucanwatchthevalueofcertainexpressions.UseAddtotypeinsomeexpressionwhosevalueisshownineachstepofthegame.Inthiswayyoucanseewhetheryourgameisdoingthingstherightway.Youcanwatchmanyexpressions.Youcansavethemforlateruse(e.g.afteryoumadeacorrectiontothegame).UndertheToolsmenuyoufinditemstoseeevenmoreinformation.Youcanseealistofallinstancesinthegame,youcanwatchallglobalvariables(well,themostimportantones)andthelocalvariablesofaninstance(eitherusetheobjectnameortheidoftheinstance).Youcanalsoviewmessageswhichyoucansendfromyourcodeusingthefunctionshow_debug_message(str).Finallyyoucangivethegame

Page 171: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

commandsandchangethespeedofthegame.Ifyoumakecomplicatedgamesyoushouldreallylearnhowtousethedebugoptions.

Page 172: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ExtensionPackages

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

ExtensionpackagesextendthepossibilitiesofGameMaker.AnextensionpackagecanaddasetofactionstoGameMakeroritaddsanumberofadditionalfunctionsandconstantstotheGMLlanguagebuiltintoGameMaker.Whenextensionpackagesareavailabletoyou,helpabouttheseisplacedintheHelpmenu.

WhendoubleclickingontheExtensionPackagesresourceitemthefollowingformisshown:

Inthisformyoucanindicatewhichextensionpackagesmustbeusedinthegame.OntheleftthereisthelistofUsedpackagesandontherightisthelistofAvailablepackages.Tomoveapackagefromonelisttotheother,simplyselectitandpressthebuttonbetweenthelist.Whenselectingapackageashortdescriptionisgivenatthebottom.FurtherhelpisavailablebypressingtheHelpbutton.

Page 173: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ExtensionpackagesareanextremelypowerfulpartofGameMaker.AfewextensionpackagesareprovidedwithGameMakerbutmanymorewillbecomeavailablethroughthewebsite.Toinstallnewpackagesoruninstallexistingones,presstheInstallbutton.Thefollowingformisshown

Youwillseealistofallextensionpackagesinstalled.ByselectingapackageandclickingtheUninstallbuttonthepackageisremovedfromthesystem.

Installpackagesaredistributedintheformofa.gexfile.YoucanfindanumberofsuchpackagesonourwebsitewhichyoucangotobypressingthebuttonFindMore.Onceyoudonwloadedsuchapackagefileonyourcomputer,presstheInstallbuttonandselectthepackagefile.Itwillthenbeinstalledinthesystem.

Ifyouwanttocreateyourownextensionpackages,pleasecheckouttheinformationthatisavailableonhttp://www.yoyogames.com/extensions.

Page 174: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Exportingandimportingresources

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Note:Importandexportofresourcesisonlyforexperiencedusers.Carefullyreadthissectionbeforeusingthesefeatures.Also,alwaysmakeaback-upcopyofyourgamebeforeimportingresources.

Sometimesyouwanttocopycertainresources(sprites,sounds,rooms,etc.)fromonegametoanothergame.Forexamplewhenyouwanttocreateanewgameusingthesamespritesandsoundsasanothergame.Orwhenyouareworkingtogetheronagame.Oneofyoumighthavecreatedsomeadditionalroomsthatyouthenwanttoimportintheothergame.TothisendGameMakerhascommandstoimportandexportresources.

Exportingresources

Toexportresources,chooseExportResourcesfromtheFilemenu.Firstofallitischeckedwhetherallresourceshavedifferentnames.Becauseresourcesinonegamearelinkedtotheonesintheothergamebyname,itisessentialthatallresourceshavedifferentnames.Ifnot,yougetanerrormessageandnoresourcescanbeexported.Otherwise,afileselectorisshowninwhichyoucanindicatethenameofthefileinwhichyouwanttoexporttheresources.Thesefilesmustendwiththeextension.gmres.Nextthefollowingformisshown:

Page 175: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Inthisformyoucanindicatewhichresourcesmustbeexported.Defaultallareexportedbutyoucanselecttheparticulartypesofresourcesyouwanttoexport.Caremustbetakenwhenexportingobjects,timelines,orrooms.Thesewillrefertosprites,sounds,triggers,etc.Soifyoudonotexporttheseotherresourcesaswellyoumustbecertainthattheseotherresourcesalreadyexistinthegameinwhichyouaregoingtoimporttheresources(underthesamenames).Ifyouareuncertain,betterexporteverything.

Importingresources

OnceyouhaveafilecontainingresourcesyoucanimporttheminadifferentgamebychoosingImportResourcesfromtheFilemenu.Firstofallitischeckedwhetherallresourceshavedifferentnames.Again,becauseresourcesinonegamearelinkedtotheonesintheothergamebyname,itisessentialthatallresourceshavedifferentnames.Ifnot,yougetanerrormessageandnoresourcescanbeimported.Otherwise,afileselectorisshowninwhichyoucanindicatethenameofthefilefromwhichyouwanttoimporttheresources.Thesefileswillendwiththeextension.gmres.Nextallopenpropertyformsareclosed.Thisisnecessarybecauseimportedresourcesmightreplaceexistingones.Nextthefollowingformisshown:

Page 176: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Alltypesofresourcesinthefileareshown.(Theonesthatwerenotexportedandgrayedout.)Youcanselectwhichoftheseresourcesyouwanttoimport.Mostofthetimeyouwanttoimportallbutsometimesyouwanttomakeaselection.Becarefulwhenimportingobjects,rooms,ortimelineswhilenotimportingotherresources.Asindicatedabovethiscanleadtoproblemsiftheresourcestheyrefertodonotexistinyourgameunderthesamename.Insuchacasetheywillbereplacedbynon-existingresources.(Forexample,intheroomsitmeansthecorrespondinginstanceswillberemoved.)

Whenresourcesinthefilehavethesamenameasresourcesinthegameanamingconflictappears.Youcanindicatehowthatshouldberesolved.Thedefaultisthatyoukeeptheresourcethatwaschangedlast.Youcanhoweveralsochoosetoalwayskeeptheoriginalinthegameoralwaysreplaceitwiththeresourceinthefile.Afourthoptionistokeepboth.Onlyusethiswhenitisabsolutelynecessary,becauseyouwillnowendupwithmultipleresourceswiththesamenamewhichcanleadtoconflictswhenreferringtothem.Whenyouimportresourcesintoanemptygame,betterchoosetoalwaysreplacethem.(Thismaysoundstrangebutforexampleotherwisetheglobalgamesettingswillnotbereplacedasthenewemptygameisofamorerecentdate!)

Finallyyoucanindicatewhethertoplacethenewresources(thatis,theonesthatdonotalreadyoccur)inanewgroup.Thismightbeusefulto

Page 177: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

distinguish(visually)theimportedresourcesfromtheexistingones.Ifyoucheckthisboxthenewresourceswillbeplaceinagroup.Thenameofthisgroupisthenameoftheimportfile.

OnceyoupressOKtheresourcesareaddedtothegame,replacingexistingresourceswiththesamenamewhenrequired.Youwillseethemappearintheresourceselectorattheleft.

WarningsandRemarks

Importingandexportingresourcesisapowerfulmechanism,inparticularwhenyouareworkingonagamewithmultiplepeople.However,ifyoudonotunderstandwhatyouaredoingitmightleadtoerrorsandfrustration.Herearesomeimportantwarningsthatyoushouldreadandunderstand.

Alwaysmakeabackupcopyofyourgamebeforeimportingresources.Otherwiseyourhardworkmightbelost.Youcannotundotheimportofresources.Alwayscheckafteranimportwhethereverythingwasimportedcorrectly.Alsoimmediatelyrunthegametoseeifitallworks.Otherwisereturntoyourbackupcopy.Notethattheindicesofresources,instances,andtiles,mostlikelychangeintheprocesstoguaranteethattheyremainunique.Thiswillcauseproblemswhenyourefertoresources(orinstances)bynumber.Alsoitwillcauseproblemsifyouassumeanythingabouttheorderinwhichinstancesarecreated.Notethattheresourceswillbeaddedintheorderinwhichtheyaregivenintheresourcelist/tree.Newresourceswillbeaddedattheend.However,thegroupstructureismaintained.Thisisnormallywhatyouexpectbutinsomerarecasesyoumighthavetomoveresourcestoadifferentlocation.Forexample,whenyouhaveastartroom,anendroomandsomeroomsinbetween,whensomebodyaddssomerooms(inbetween)andyouthenexporttheseandimportthemintheoriginalgame,theywillappearattheend(becausetheyarenew).Youthenmustmovetheendroomtothe

Page 178: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

appropriatelocationagain.!Notethatconstantsandtriggersonlygloballystoreinformationaboutwhentheywerelastchanged.Sowhenyouchangeoneconstantoronetrigger,allwillbereplacedwhenchoosingKeepLastChanged.Fortheglobalgamesettingsthesameholds.Theyareeitherall,ornotatallreplaced.Notethatanemptygamewillhaveanewdateatwhichitwaslastchanged.Thismeansthatifyouimportresourcesinanewemptygame,theconstants,triggers,andglobalgamesettingswillnotbeimported,unlessyousetthenameconflicthandlingtoalwaysreplace.Don'tremoveresourcesfromagamebeforeimportingthesameresourcesagain!Thismightsoundalogicalthingtodobutitwillnotwork.Onceyouremovearesourcefromagameitnolongerexists.Henceallreferencestoitwillbecomeundefined.Importingthesameresourcelaterwillnotrestorethosereferencesbecausetheprogramcannotknowitisthesameresource.Insteadlettheimportfeaturereplacetheresources.Ifyouhaveworkedonagameforalongtimeaddinganddeletingmanyresources,itisusefultocompletelyexportitandthenimportitintoanemptygame(withtheoptiontoalwaysreplace).Thegamewillworkasbeforebutwillbestrippedoflotsofunuseddata.

Page 179: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Polishingyourgame

Whenyouwanttodistributeyourgameyoubettermakesurethatithasalltheingredientsthatmakeitagreatgame.Besidesthegameitselfthismeansthatyoushouldprovidegameinformation,setthecorrectglobalgamesettings,andtakecareofspeed.Thissectiongivesyouinformationabouttheseaspects.

Informationonfinishingyourgamecanbefoundinthefollowingpages:

GameInformationGlobalGameSettingsSpeedConsiderations

Page 180: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Gameinformation

Agoodgameprovidestheplayerwithsomeinformationonhowtoplaythegame.Thisinformationisdisplayedwhentheplayerpressesthe<F1>keyduringgameplay.GameMakerhasasimplebuilt-inmechanismtoprovidegamehelp.However,itislimitedinfunctionality.Tocreatenicergamesitisbettertocreatethehelpyourselfusingspecialroomsorbyusingsplashscreenwithe.g.htmlpages.

Tocreatethesimplegameinformation,doubleclickGameInformationintheresourcetreeattheleftofthescreen.Alittlebuilt-ineditorisopenedwhereyoucaneditthegameinformation.Youcanusedifferentfonts,differentcolors,andstyles.Alsoyoucansetthebackgroundcolor.

IntheFilemenuyoucanalsosetanumberofOptions.Defaultthehelpisshowninthegamewindowandgameplayistemporarilyhalted.Hereyoucanindicatetoshowthehelpfileinaseparatewindow.Inthiscaseyoucanindicatethecaptionofthegameinformationduringthegame.Alsoyoucanindicatetheposition(use-1forcentered)andsizeofthegameinformationwindowandwhetheritshouldhaveaborderandbesizeablebytheplayer.Youcanforcetheinformationwindowtostayontopandyoucanindicatewhetherthegameshouldcontinueplayingwhile

Page 181: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

theinformationisshown.

Goodadviceistomaketheinformationshortbutprecise.Ofcourseyoushouldaddyournamebecauseyoucreatedthegame.Allexamplegamesprovidedhaveaninformationfileaboutthegameandhowitwascreated.YoumightwanttoindicateatthebottomofthehelpfilethattheusermustpressEscapetocontinueplaying.)

Ifyouwanttomakeabitmorefancyhelp,useaprogramlikeWord.ThenselectthepartyouwantandusecopyandpastetomoveitfromWordtothegameinformationeditor.Formoreadvancedgamesthoughyouprobablywillnotusethismechanismatallbutusesomededicatedroomstoshowhelpaboutthegame.

Page 182: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

GlobalGameSettings

Thereareanumberofsettingsyoucanchangeforyourgame.Thesechangetheshapeofthemainwindow,setsomegraphicsoptions,dealwithinteractionsettings,toloadingimage,constantsandinformationaboutthecreatorofthegame.Alsoyoucanindicateherewhichfilesshouldbeincludedinstand-alonegamesandhowerrorsshouldbehandled.

ThesettingscanbechangedbydoubleclickingonGlobalGameSettingsintheresourcetreeattheleftofthescreen.Theyaresubdividedinanumberoftabbedpages.(Someoptionsareonlyavailableinadvancedmode.)

Informationaboutthedifferentsettingscanbefoundinthefollowingpages:

GraphicsandWindowOptionsTheScreenResolutionVariousOtherOptionsLoadingOptionsErrorOptionsInformationabouttheGame

Page 183: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Graphicsoptions

Inthistabyoucansetanumberofoptionsthatarerelatedtothegraphicalappearanceofyourgame.Itisnormallyusefultocheckouttheeffectsoftheseoptionsbecausetheycanhaveasignificanteffectonthewaythegamelooks.Rememberthoughthatdifferentusershavedifferentmachines.Sobettermakesurethatthesettingsalsoworkonotherpeoplesmachines.

StartinfullscreenmodeWhencheckedthegamerunsinthefullscreen;otherwiseitrunsinawindow.

ScalingHereyoucanindicatewhathappenswhenthewindowislargerthantheroomorwhenthegameisruninfull-screenmode.Therearethreechoices.Youcanindicateafixedscaling.Theroomisdrawnscaledwiththegivenamountinthecenterofthewindoworthecenterofthescreen.100indicatesnoscaling.Youtypicallyusefixedscalingwhenyourspritesandroomsareverysmall.Thesecondoptionisscaletheroomsuchthatitfillsthewindoworscreenbutkeeptheaspectratio(ratiobetweenwidthandheight)thesame.Thethirdoptionistoscalesuchthatthewindoworscreeniscompletelyfilled.Thiscanleadtodistortionsintheimage(inparticularinwindowedmodewhentheusercanresizethewindow).

InterpolatecolorsbetweenpixelsWhenchecked,colorsofpixelsinsprites,backgrounds,andtilesthatarenotalignedwithpixelsonthescreenwillbeinterpolated.Thisinparticularisthecasewhentheyarescaled,rotated,orplacedatnon-integerpositions.Interpolationmakesmovementsmootherbutcanalsogiveablurredeffect.(Alsofortilesitcanleadtocracksbetweenthem,ifnotcarefullydesigned.)

ColoroutsidetheroomregionWhentheroomdoesnotcompletelyfillthewindoworscreenthereissomeareaunusedaroundit.Hereyoucanspecifythecolorofthearea.

Page 184: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

AllowtheplayertoresizethegamewindowWhencheckedinwindowedmodetheusercanchangethesizeofthegamewindowbydraggingwiththemouseatitscorners.

LetthegamewindowalwaysstayontopWhencheckedinwindowedmodethegamewindowalwaysstaysontopofotherwindows.

Don'tdrawaborderinwindowedmodeWhencheckedinwindowedmodethegamewindowwillnothaveaborderoracaptionbar.

Don'tshowthebuttonsinthewindowcaptionWhencheckedinwindowedmodethewindowcaptionwillnotshowthebuttonstoclosethewindowortominimizeormaximizeit.

DisplaythecursorIndicateswhetheryouwantthemousepointertobevisible.Turningitoffisnormallyfasterandnicer.(YoucaneasilymakeyouowncursorobjectinGameMaker.)

FreezethegamewhentheformlosesfocusWhenchecked,whenevertheplayerbringssomeotherformtothetop(e.g.anotherapplication)thegamefreezesuntilthegamewindowagaingetsthefocus.

DisablescreensaversandpowersavingactionsWhenchecked(default)screensaversorpowersavingactions(sleep,hibernate)willnotactivatewhilethegameisrunning.Thisisimportantasthesemightdestroycertaingraphicsaspectsofthegame(likesurfaces).

Page 185: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Resolution

Inthistabyoucansetthescreenresolutioninwhichyourgamemustrun.Bydefaulttheresolutionisnotchanged.Butsometimesyouwanttorunthegameinalowerresolutionsoryouwanttosetthefrequencyofthemonitortomakesurethetiminginthegameworkscorrectly.IfyouwanttochangetheresolutionyoumustfirstchecktheboxlabeledSettheresolutionofthescreen.

Therearethreethingsyoucanchange.Firstofallthereisthecolordepth.Thisindicatesthenumberofbitsusedtorepresentthecolorforapixel.Mostmachinesnowonlyallowfor16-bit(HighColor)or32-bit(FullColor)butoldermachinesalsoallowedfor8-bitandsometimes24-bitcolor.GameMakeronlyworkscorrectlyin16-bitand32-bitcolor.32-bitcolorgivesnicerlookingimagesbutwilltakemorememoryandprocessingtime.Ifyouwantyourgametorunwillonmostoldermachinessetthecolordepthto16-bit.Otherwiseuse32-bitordon'tchangeit.

Secondlythereisthescreenresolution,thenumberofpixels(horizontalandvertical)onthescreen.Changingtheresolutionisusefulwhene.g.yourroomsareverysmall.Inthiscaseitmighthelptoreducetheresolutionofthescreen.Realizethoughthatthiswillalsoeffectotherapplicationsrunning.Thiscaninparticulargiveproblemswithlowresolutions.Soingeneralitisbettertoonlydothiswhenrunningthegameinfullscreenmode.GameMakerwillautomaticallychangetheresolutionbacktothestartingsituationoncethegamefinishes.

Finallyyoucanchangetherefreshfrequency.Thisindicateshowmanytimespersecondtheimageonthescreenisrefreshed.Ifyourroomspeedislargerthanthefrequencynotallstepsareactuallyvisible.Itworksbestifthefrequencyisamultipleoftheroomspeed.(Ifyouspecifyafrequencythatistoohighornotavailablethefrequencyisnotchanged.)

TherealsoisasettingheretoUsesynchronizationtoavoidtearing.

Page 186: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thisrequiressomeexplanation.Adisplayisredrawnanumberoftimespersecond,dependingontherefreshfrequency.Ifaroomisdrawnhalfwaysucharefresh,thetopofthedisplaywillstillshowtheoldimagewhilethebottompartshowsthenewimage.Thisiscalledtearing.Toavoidthisyoucancheckthisoption.Inthiscasethenewroomimageisonlycopiedtothescreenwhentherefreshisnotinsidethewindowavoidingthetearingmostofthetime.Thedisadvantageisthatwenormallyhavetowaittillthenextrefresh.Thismeansthatthemaximalnumberofframesisboundedbythefrequencyofthemonitorand,whentheprocessingisnotfastenough,theframerateimmediatelydropstohalfthatnumber.Alsotherecanbeaconflictbetweentheinternaltimingofthegameandthesynchronization.Ifyouwanttodothisbestsetthemonitorfrequencytoe.g.60andalsomaketheroomspeedeither30or60.

Page 187: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Variousotheroptions

Hereyoucansetanumberofadditionaloptions.Firstofallyoucansetsomedefaultkeys:

Let<Esc>endthegameWhenchecked,pressingtheescapekeywillendthegame.Moreadvancedgamesnormallydon'twantthistohappenbecausetheymightwanttodosomeprocessing(likesaving)beforeendingthegame.Inthiscase,uncheckthisboxandprovideyourownactionsfortheescapekey.

Treattheclosebuttonas<Esc>keyWhencheckedtheclosebuttonofthewindowwillgenerateanescapekeyevent.Whennotcheckedtheclosebuttoneventsarecalledinstead.

Let<F1>showthegameinformationWhencheckedpressingtheF1keywilldisplaythegameinformation.

Let<F4>switchbetweenscreenmodesWhencheckedtheF4keywillswitchbetweenfullscreenandwindowedmode.

Let<F5>savethegameand<F6>loadagameWhencheckedtheplayercanuse<F5>tostorethecurrentgamesituationand<F6>toloadthelastsavedgame.(Notethatonlythebasicgamedataisstored.Onceyouuseadvancedfeatureslikeparticlesordatastructuresthosesettingsarenotsavedandyoumighthavetocreateasavemechanismyourself.

Let<F9>takeascreenshotofagameWhencheckedtheplayercanuse<F9>tocreateascreenshotofthegame.ThisscreenshotwillbeplaceinthefilescreenshotXXX.pnginthefolderwherethegameisrunning,whereXXXisthenumberofthescreenshot.Whencreatingmultiplescreenshotthenumberisautomaticallyincreased.

Page 188: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Alsoyoucansetthepriorityofthegameprocess.Thispriorityindicateshowmuchprocessortimeisallottedtothegame.Innormalmodetheoperatingsystemtriestogiveprocessortimetoeachprocessthatneedsitinsomereasonableway.Thehigheryouputtheprioritythemoretimeisallottedtothegame,makingitrunmoresmoothlyandfaster.Butotherprocessesgetlesstime(alsoWindowsprocessessoeventhemousemightnotmoveanymore).Usethiswithcare.

Finally,youcansettheversioninformationofthegame.Thisinformationisshowninthehelptipthatpopsupwhentheuserrestshismouseonthegameexecutable.Itisalsoshownwhentheusersclickswiththerightmousebuttonontheprogramandchoosespropertiesandthenversion.Ifyoudistributeyourgameyoubestfillinthisinformation.

Youshouldgiveyourgameaversionnumberthatconsistsoffourparts:themajorversion,theminorversion,thereleasenumberandthebuildnumber.Alsoyoushouldprovidethenameofthecompany(you),thenameoftheproduct,thecopyrightinformation,andaverybriefdescription.Allthesefieldsshouldbeatmost64characterslong.

Page 189: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Loadingoptions

Hereyoucanindicatewhatshouldhappenwhenloadingagame.Firstofallyoucanspecifyyourownloadingimage.Secondly,youcanindicatewhethertodisplayaloadingprogressbaratthebottomoftheimage.Youhavethreeoptionshere.Eithernoloadingbarisdisplayed,orthedefaultbarisdisplayedoryoucanspecifytwoimages:thebackgroundoftheloadingbarandtheforeground.Youcanindicatewhetherthefrontloadingbarmustbescaled(default)orclippedwhileitbecomeslonger.Inthesecondcase,makesureenoughtheimageislargeenoughtofillthebar.(Notethatbothimagesmustbespecifiedinthiscase,notjustone.)

Itispossibletoindicatethattheloadingimagemustbetransparent.Inthiscasetheleftbottompixelofthebackgroundimageisusedastransparentcolor.(Notethattransparencyfrome.g.pngorgiffilesisnottakenintoaccounthere!)Alsothealphatranslucencycanbeindicated.Avalueof0meansfullytranslucent.Avalueof255meansfullyopaque.(BothonlyworkunderWindows2000,XP,orlater.)

Secondly,youcanindicateheretheiconthatshouldbeusedforstand-alonegames.Youriconsmustcontainatleasta32x32icon,buttheycanalsocontainlargerones.Ifyoutrytoselectanothertypeoficonyouwillgetawarning.

Finallyyoucanchangetheuniquegameid.Thisidisusedforstoringthehighscorelistandsavegamefiles.Ifyoureleaseanewversionofyourgameanddon'twanttotakeovertheoldhighscorelist,youshouldchangethisnumber.

Page 190: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Erroroptions

Hereyoucansetanumberofoptionsthatrelatetothewayerrorsarereported.

DisplayerrormessagesWhenchecked,errormessagesareshowntotheplayer.Inthefinalversionofthegameyoumightwanttouncheckthisoption.

Writeerrormessagestofilegame_errors.logWhencheckedallerrormessagesarewrittentoafilecalledgame_errors.loginthegamefolder.

AbortonallerrormessagesNormally,certainerrorsarefatalwhileotherscanbeignored.Whencheckingthisoptionallerrorsareconsideredfatalandleadtoabortingthegame.Inthefinalversionofthegameyoudistributeyoumightwanttocheckthisoption.

Treatuninitializedvariablesas0Onecommonerroristouseavariablebeforeavalueisassignedtoit.Sometimesthisisdifficulttoavoid.Whencheckingthisoptionsuchuninitializedvariablesnolongerreportanerrorbutaretreatedasvalue0.Becarefulthough.Itmightmeanthatyoudon'tspottypingmistakesanymore.

Page 191: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Informationaboutthegame

Hereyoucanindicatetheauthorofthegame,theversionofthegame,andsomeinformationaboutthegame.Alsothelastchangeddateismaintained.Thisisusefulifyouareworkingwithmanypeopleonagameormakenew,updatedversion.Theinformationisnotaccessiblewhenthegameisrunning.

Page 192: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Speedconsiderations

Ifyouaremakingcomplicatedgamesyouprobablywanttomakethemrunasfastaspossible.EventhoughGameMakerdoesitsbesttomakegamesrunfast,alotdependsonhowyoudesignyourgame.Also,itisrathereasytomakegamesthatuselargeamountsofmemory.Inthispagewegivesomehintsonhowtomakeyourgamesfasterandsmaller.

Firstofall,lookcarefullyatthespritesandbackgroundsyouuse.Animatedspritestakealotofmemoryanddrawinglotsofspritestakesalotoftime.Somakeyourspritesassmallaspossible.Removeanyinvisibleareaaroundit(thecommandCropinthespriteeditordoesthatautomatically).Thesameappliestobackgroundimages.Ifyouhaveacoveringbackground,makesureyouswitchofftheuseofabackgroundcolor.

Ifyouusefullscreenmode,makesurethesizeoftheroom(orwindow)isneverlargerthanthescreensize.Mostgraphicscardscanefficientlyscaleimagesupbuttheyaremoreslowinscalingimagesdown!Wheneverpossible,switchoffthecursor.Itslowsdownthegraphics.

Alsobecarefulwiththeuseofmanyviews.Foreachviewtheroomisredrawn.

Besidesthegraphics,therearealsootheraspectsthatinfluencethespeed.Makesureyouhaveasfewinstancesaspossible.Inparticular,destroyinstancesoncetheyarenolongerrequired(e.g.whentheyleavetheroom).Avoidlotsofworkinthestepeventordrawingeventofinstances.Oftenthingsdonotneedtobecheckedineachstep.Interpretationofcodeisreasonablyfast,butitisinterpreted.Also,somefunctionsandactionstakealotoftime;inparticularthosethathavetocheckallinstances(likeforexamplethebounceaction).

Whenyouneedcomplicatedprocessing(forexampleforadvancedAI),youbetterwriteaDLLforthisinadifferentlanguageandcreateanextensionpackageoutofthistoimporttheDLLusingthefunctions

Page 193: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

describedinthepageonUsingDLL's.

Thinkaboutwheretotreatthecollisionevents.Younormallyhavetwooptions.Objectsthathavenocollisioneventsaretreatedmuchfaster,sopreferablytreatcollisionsinthoseobjectsofwhichtherearejustafewinstances.

Becarefulwithusinglargesoundfiles.Theytakealotofmemoryandalsocompressbadly.Youmightwanttocheckyoursoundsandseewhetheryoucansamplethemdown.

Finally,ifyouwanttomakeagamethatmanypeoplecanplay,makesureyoutestitonanumberofdifferentmachines,inparticularalsooldermachines.

Page 194: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

TheGameMakerLanguage(GML)

GameMakercontainsabuilt-inprogramminglanguage.Thisprogramminglanguagegivesyoumuchmoreflexibilityandcontrolthanthestandardactions.ThislanguagewewillrefertoasGML(theGameMakerLanguage).InthissectionwedescribethelanguageGMLandwegiveanoverviewofallthe(closeto1000)functionsandvariablesavailabletocontrolallaspectsofyourgame.

InformationonGMLcanbefoundinthefollowingpages:

LanguageoverviewComputingthingsGameplayUserinteractionGamegraphicsSoundandmusicSplashscreens,highscoresandotherpop-upsResourcesChangingresourcesFiles,registry,andexecutingprogramsDatastructuresCreatingparticlesMultiplayergamesUsingDLL's3DGraphics

Page 195: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

GMLLanguageoverview

GameMakercontainsabuilt-inprogramminglanguage.Thisprogramminglanguagegivesyoumuchmoreflexibilityandcontrolthanthestandardactions.ThislanguagewewillrefertoasGML(theGameMakerLanguage).Thereareanumberofdifferentplaceswhereyoucantypeprogramsinthislanguage.Firstofall,whenyoudefinescripts.AscriptisaprograminGML.Secondly,whenyouaddacodeactiontoanevent.InacodeactionyouagainhavetoprovideaprograminGML.Thirdly,intheroomcreationcode.Andfinally,whereveryouneedtospecifyavalueinanaction,youcanalsouseanexpressioninGML.Anexpression,aswewillseebelowisnotacompleteprogram,butapieceofcoderesultinginavalue.

InthischapterwewilldescribethebasicstructureofprogramsinGML.WhenyouwanttouseprogramsinGML,thereareacoupleofthingsyouhavetobecarefulabout.Firstofall,forallyourresources(sprites,objects,sounds,etc.)youmustusenamesthatstartwithaletterandonlyconsistofletters,digitsandtheunderscore'_'symbol.Otherwiseyoucannotrefertothemfromwithintheprogram.Makesureallresourceshavedifferentnames.Alsobecarefulnottonameresourcesself,other,global,orallbecausethesehavespecialmeaninginthelanguage.Alsoyoushouldnotuseanyofthekeywords,indicatedbelow.

InformationontheGMLlanguagecanbefoundinthefollowingpages:

AProgramVariablesAssignmentsExpressionsExtraVariablesAddressingVariablesinOtherInstancesArraysIfStatementRepeatStatementWhileStatement

Page 196: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

DoStatementForStatementSwitchStatementBreakStatementContinueStatementExitStatementFunctionsScriptsWithConstructionCommentFunctionsandVariablesinGML

Page 197: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Aprogram

Aprogramconsistsofasetofinstructions,calledstatements.Aprogrammuststartwiththesymbol'{'andendwiththesymbol'}'.Betweenthesesymbolstherearethestatements.Statementsmustbeseparatedwitha';'symbol.Sotheglobalstructureofeveryprogramis:

{

<statement>;

<statement>;

...

}

Thereareanumberofdifferenttypesofstatements,whichwillbediscussedbelow.

Page 198: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Variables

LikeanyprogramminglanguageGMLcontainsvariables.Variablesarememorylocationsthatstoreinformation.Theyhaveanamesothatyoucanrefertothem.AvariableinGMLcanstoreeitherarealnumberorastring.Variablesdonotneedtobedeclaredlikeinmanyotherlanguages.Therearealargenumberofbuilt-invariables.Somearegeneral,likemouse_xandmouse_ythatindicatethecurrentmouseposition,whileallothersarelocaltotheobjectinstanceforwhichweexecutetheprogram,likexandythatindicatethecurrentpositionoftheinstance.Avariablehasanamethatmuststartwithaletterandcancontainonlyletters,numbers,andtheunderscoresymbol'_'.(Themaximallengthis64symbols.)Whenyouuseanewvariableitislocaltothecurrentinstanceandisnotknowninprogramsforotherinstances(evenofthesameobject).Youcanthoughrefertovariablesinotherinstances;seebelow.

Page 199: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Assignments

Anassignmentstoresavalueinavariable.Anassignmenthastheform:

<variable>=<expression>;

Anexpressioncanbeasimplevaluebutcanalsobemorecomplicated.Ratherthanassigningavaluetoavariable,onecanalsoaddthevaluetothecurrentvalueofthevariableusing+=.Similar,youcansubtractitusing-=,multiplyitusing*=,divideitusing/=,orusebitwiseoperatorsusing|=,&\,or^=.

Page 200: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Expressions

Expressionscanberealnumbers(e.g.3.4),hexadecimalnumbers,startingwitha$sign(e.g.$00FFAA),stringsbetweensingleordoublequotes(e.g.'hello'or“hello”)ormorecomplicatedexpressions.(Notethatstringscanrunovermultiplelines!)Forexpressions,thefollowingbinaryoperatorsexist(inorderofpriority):

&&||^^:combineBooleanvalues(&&=and,||=or,^^=xor)<<===!=>>=:comparisons,resultintrue(1)orfalse(0)|&^:bitwiseoperators(|=bitwiseor,&=bitwiseand,^=bitwisexor)<<>>:bitwiseoperators(<<=shiftleft,>>=shiftright)+-:addition,subtraction*/divmod:multiplication,division,integerdivision,andmodulo

Notethatvalueofxdivyisthevalueofx/yroundedinthedirectionofzerotothenearestinteger.Themodoperatorreturnstheremainderobtainedbydividingitsoperands.Inotherwords,xmody=x-(xdivy)*y.Also,thefollowingunaryoperatorsexist:

!:not,turnstrueintofalseandfalseintotrue-:negatesthenextvalue~:negatesthenextvaluebitwise

Asvaluesyoucanusenumbers,variables,orfunctionsthatreturnavalue.Sub-expressionscanbeplacedbetweenbrackets.Alloperatorsworkforrealvalues.Comparisonsalsoworkforstringsand+concatenatesstrings.(Pleasenotethat,contrarytocertainlanguages,bothargumentstoaBooleanoperationarealwayscomputed,evenwhenthefirstargumentalreadydeterminestheoutcome.)

Example

Hereisanexamplewithsomeassignments.

Page 201: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

{

x=23;

color=$FFAA00;

str='helloworld';

y+=5;

x*=y;

x=y<<2;

x=23*((2+4)/sin(y));

str='hello'+"world";

b=(x<5)&&!(x==2||x==4);

}

Page 202: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Extravariables

Youcreatenewvariablesbyassigningavaluetothem(noneedtodeclarethemfirst).Ifyousimplyuseavariablename,thevariablewillbestoredwiththecurrentobjectinstanceonly.Sodon'texpecttofinditwhendealingwithanotherobject(oranotherinstanceofthesameobject)later.Youcanalsosetandreadvariablesinotherobjectsbyputtingtheobjectnamewithadotbeforethevariablename.

Tocreateglobalvariables,thatarevisibletoallobjectinstances,precedethemwiththewordglobalandadot.Soforexampleyoucanwrite:

{

if(global.doit)

{

//dosomething

global.doit=false;

}

}

Alternativelyyoucandeclarethevariablesasbeingglobal.Thisdeclarationlooksasfollows.

globalvar<varname1>,<varname2>,<varname3>,...;

Oncethisdeclarationhasbeenexecuted,thevariableisalwaystreatedasglobalwithouttheneedtoputthewordglobalandadotinfrontofit.Itonlyneedstobedeclaredonceinapieceofcodethatisexecuted.Afterthatinallotherplacesthevariableisconsideredasbeingglobal.

Sometimesyouwantvariablesonlywithinthecurrentpieceofcodeorscript.Inthiswayyouavoidwastingmemoryandyouaresurethereisnonamingconflict.Itisalsofasterthanusingglobalvariables.Toachievethisyoumustdeclarethevariablesatthebeginningofthepieceofcodeusingthekeywordvar.Thisdeclarationlooksasfollows.

var<varname1>,<varname2>,<varname3>,...;

Page 203: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Forexample,youcanwrite:

{

varxx,yy;

xx=x+10;

yy=y+10;

instance_create(xx,yy,ball);

}

Page 204: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Addressingvariablesinotherinstances

Asdescribedearlier,youcansetvariablesinthecurrentinstanceusingstatementslike

x=3;

Butinanumberofcasesyouwanttoaddressvariablesinanotherinstance.Forexample,youmightwanttostopthemotionofallballs,oryoumightwanttomovethemaincharactertoaparticularposition,or,inthecaseofacollision,youmightwanttosetthespritefortheotherinstanceinvolved.Thiscanbeachievedbyprecedingthevariablenamewiththenameofanobjectandadot.Soforexample,youcanwrite

ball.speed=0;

Thiswillchangethespeedofallinstancesofobjectball.Thereareanumberofspecial"objects".

self:Thecurrentinstanceforwhichweareexecutingtheactionother:Theotherinstanceinvolvedinacollisioneventall:Allinstancesnoone:Noinstanceatall(soundsweirdprobablybutitdoescomeinhandyaswewillseelateron)global:Notaninstanceatall,butacontainerthatstoresglobalvariables

So,forexample,youcanusethefollowingkindofstatements:

other.sprite_index=sprite5;

all.speed=0;

global.message='Agoodresult';

global.x=ball.x;

Nowyoumightwonderwhatthelastassignmentdoeswhentherearemultipleballs.Well,thefirstoneistakenanditsxvalueisassignedtothe

Page 205: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

globalvalue.

Butwhatifyouwanttosetthespeedofoneparticularball,ratherthanallballs?Thisisslightlymoredifficult.Eachinstancehasauniqueid.Whenyouputinstancesinaroominthedesigner,thisinstanceidisshownwhenyourestthemouseontheinstance.Thesearenumberslargerthanorequalto100000.Suchanumberyoucanalsouseastheleft-handsideofthedot.Butbecareful.Thedotwillgetinterpretedasthedecimaldotinthenumber.Toavoidthis,putbracketsaroundit.Soforexample,assumingtheidoftheballis100032,youcanwrite:

(100032).speed=0;

Whenyoucreateaninstanceintheprogram,thecallreturnstheid.Soavalidpieceofprogramis

{

nnn=instance_create(100,100,ball);

nnn.speed=8;

}

Thiscreatesaballandsetsitsspeed.Notethatweassignedtheinstanceidtoavariableandusedthisvariableasindicationinfrontofthedot.Thisiscompletelyvalid.Letustrytomakethismoreprecise.Adotisactuallyanoperator.Ittakesavalueasleftoperandandavariable(address)asrightoperand,andreturnstheaddressofthisparticularvariableintheindicatedobjectorinstance.Alltheobjectnames,andthespecialobjectsindicatedabovesimplyrepresentvaluesandthesecanbedealtwithlikeanyvalue.Forexample,thefollowingprogramisvalid:

{

obj[0]=ball;

obj[1]=flag;

obj[0].alarm[4]=12;

obj[1].id.x=12;

}

Thelaststatementshouldbereadasfollows.Wetaketheidofthefirstflag.Fortheinstancewiththatidwesetthexcoordinateto12.

Page 206: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Objectnames,thespecialobjects,andtheinstanceid'scanalsobeusedinanumberoffunctions.Theyareactuallytreatedasconstantsintheprograms.

Page 207: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Arrays

Youcanuse1-and2-dimensionalarraysinGML.Simplyputtheindexbetweensquarebracketsfora1-dimensionalarray,andthetwoindiceswithacommabetweenthemfor2-dimensionalarrays.Atthemomentyouuseanindexthearrayisgenerated.Eacharrayrunsfromindex0.Sobecarefulwithusinglargeindicesbecausememoryforalargearraywillbereserved.Neverusenegativeindices.Thesystemputsalimitof32000oneachindexand1000000onthetotalsize.Soforexampleyoucanwritethefollowing:

{

a[0]=1;

i=1;

while(i<10){a[i]=2*a[i-1];i+=1;}

b[4,6]=32;

}

Page 208: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Ifstatement

Anifstatementhastheform

if(<expression>)<statement>

or

if(<expression>)<statement>else<statement>

Thestatementcanalsobeablock.Theexpressionwillbeevaluated.Ifthe(rounded)valueis<=0(false)thestatementafterelseisexecuted,otherwise(true)theotherstatementisexecuted.Itisagoodhabittoalwaysputcurlybracketsaroundthestatementsintheifstatement.Sobestuse

if(<expression>)

{

<statement>

}

else

{

<statement>

}

ExampleThefollowingprogrammovestheobjecttowardthemiddleofthescreen.

{

if(x<200){x+=4}else{x-=4};

}

Page 209: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Repeatstatement

Arepeatstatementhastheform

repeat(<expression>)<statement>

Thestatementisrepeatedthenumberoftimesindicatedbytheroundedvalueoftheexpression.

ExampleThefollowingprogramcreatesfiveballsatrandompositions.

{

repeat(5)instance_create(random(400),random(400),ball);

}

Page 210: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Whilestatement

Awhilestatementhastheform

while(<expression>)<statement>

Aslongastheexpressionistrue,thestatement(whichcanalsobeablock)isexecuted.Becarefulwithyourwhileloops.Youcaneasilymakethemloopforever,inwhichcaseyourgamewillhangandnotreacttoanyuserinputanymore.

ExampleThefollowingprogramtriestoplacethecurrentobjectatafreeposition(thisisaboutthesameastheactiontomoveanobjecttoarandomposition).

{

while(!place_free(x,y))

{

x=random(room_width);

y=random(room_height);

}

}

Page 211: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Dostatement

Adostatementhastheform

do<statement>until(<expression>)

Thestatement(whichcanalsobeablock)isexecuteduntiltheexpressionistrue.Thestatementisexecutedatleastonce.Becarefulwithyourdoloops.Youcaneasilymakethemloopforever,inwhichcaseyourgamewillhangandnotreacttoanyuserinputanymore.

ExampleThefollowingprogramtriestoplacethecurrentobjectatafreeposition(thisisaboutthesameastheactiontomoveanobjecttoarandomposition).

{

do

{

x=random(room_width);

y=random(room_height);

}

until(place_free(x,y))

}

Page 212: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Forstatement

Aforstatementhastheform

for(<statement1>;<expression>;<statement2>)<statement3>

Thisworksasfollows.Firststatement1isexecuted.Thentheexpressionisevaluated.Ifitistrue,statement3isexecuted;thenstatement2andthentheexpressionisevaluatedagain.Thiscontinuesuntiltheexpressionisfalse.

Thismaysoundcomplicated.Youshouldinterpretthisasfollows.Thefirststatementinitializesthefor-loop.Theexpressiontestswhethertheloopshouldbeended.Statement2isthestepstatementthatgoestothenextloopevaluation.

Themostcommonuseistohaveacounterrunthroughsomerange.

ExampleThefollowingprograminitializesanarrayoflength10withthevalues1-10.

{

for(i=0;i<=9;i+=1)list[i]=i+1;

}

Page 213: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Switchstatement

Inanumberofsituationsyouwanttoletyouractiondependonaparticularvalue.Youcandothisusinganumberofifstatementsbutitiseasiertousetheswitchstatement.Aswitchstatementhasthefollowingform:

switch(<expression>)

{

case<expression1>:<statement1>;...;break;

case<expression2>:<statement2>;...;break;

...

default:<statement>;...

}

Thisworksasfollows.Firsttheexpressionisexecuted.Nextitiscomparedwiththeresultsofthedifferentexpressionsafterthecasestatements.Theexecutioncontinuesafterthefirstcasestatementwiththecorrectvalue,untilabreakstatementisencountered.Ifnocasestatementhastherightvalue,executioniscontinuedafterthedefaultstatement.(Itisnotrequiredtohaveadefaultstatement.)Notethatmultiplecasestatementscanbeplacedforthesamestatement.Also,thebreakisnotrequired.Ifthereisnobreakstatementtheexecutionsimplycontinueswiththecodeforthenextcasestatement.

ExampleThefollowingprogramtakesactionbasedonakeythatispressed.

switch(keyboard_key)

{

casevk_left:

casevk_numpad4:

x-=4;break;

casevk_right:

casevk_numpad6:

x+=4;break;

}

Page 214: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 215: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Breakstatement

Thebreakstatementhastheform

break

Ifusedwithinafor-loop,awhile-loop,arepeat-loop,aswitchstatement,orawithstatement,itendthislooporstatement.Ifusedoutsidesuchastatementitendstheprogram(notthegame).

Page 216: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Continuestatement

Thecontinuestatementhastheform

continue

Ifusedwithinafor-loop,awhile-loop,arepeat-loop,orawithstatement,itcontinueswiththenextvalueforthelooporwithstatement.

Page 217: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Exitstatement

Theexitstatementhastheform

exit

Itsimplyendstheexecutionofthisscriptorpieceofcode.(Itdoesnotendtheexecutionofthegame!Forthisyouneedthefunctiongame_end();seebelow.)

Page 218: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Functions

Afunctionhastheformofafunctionname,followedbyzeroormoreargumentsbetweenbrackets,separatedbycommas.

<function>(<arg1>,<arg2>,...)

Therearetwotypesoffunctions.Firstofall,thereisahugecollectionofbuilt-infunctions,tocontrolallaspectsofyourgame.Secondly,anyscriptyoudefineinyourgamecanbeusedasafunction.

Notethatforafunctionwithoutargumentsyoustillneedtousethebrackets.Somefunctionsreturnvaluesandcanbeusedinexpressions.Otherssimplyexecutecommands.

Notethatitisimpossibletouseafunctionasthelefthandsideofanassignment.Forexample,youcannotwriteinstance_nearest(x,y,obj).speed=0.Insteadyoumustwrite(instance_nearest(x,y,obj)).speed=0.

Page 219: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Scripts

Whenyoucreateascript,youwanttoaccesstheargumentspassedtoit(eitherwhenusingthescriptaction,orwhencallingthescriptasafunctionfromaprogram(orfromanother,oreventhesamescript).Theseargumentsarestoredinthevariablesargument0,argument1,...,argument15.Sotherecanbeatmost16arguments.(Notethatwhencallingthescriptfromanaction,onlythefirst5argumentscanbespecified.)Youcanalsouseargument[0]etc.

Scriptscanalsoreturnavalue,sothattheycanbeusedinexpressions.Forthisendyouusethereturnstatement:

return<expression>

Executionofthescriptendsatthereturnstatement!

ExampleHereisthedefinitionforalittlescriptthatcomputesthesquareoftheargument:

{

return(argument0*argument0);

}

Tocallascriptfromwithinapieceofcode,justactthesamewayaswhencallingfunctions.Thatis,writethescriptnamewiththeargumentvaluesinparentheses.

Page 220: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Withconstructions

Asindicatedbefore,itispossibletoreadandchangethevalueofvariablesinotherinstances.Butinanumberofcasesyouwanttodoalotmorewithotherinstances.Forexample,imaginethatyouwanttomoveallballs8pixelsdown.Youmightthinkthatthisisachievedbythefollowingpieceofcode

ball.y=ball.y+8;

Butthisisnotcorrect.Therightsideoftheassignmentgetsthevalueofthey-coordinateofthefirstballandadds8toit.Nextthisnewvalueissetasy-coordinateofallballs.Sotheresultisthatallballsgetthesamey-coordinate.Thestatement

ball.y+=8;

willhaveexactlythesameeffectbecauseitissimplyanabbreviationofthefirststatement.Sohowdoweachievethis?Forthispurposethereisthewithstatement.Itsglobalformis

with(<expression>)<statement>

<expression>indicatesoneormoreinstances.Forthisyoucanuseaninstanceid,thenameofanobject(toindicateallinstancesofthisobject)oroneofthespecialobjects(all,self,other,noone).<statement>isnowexecutedforeachoftheindicatedinstances,asifthatinstanceisthecurrent(self)instance.So,tomoveallballs8pixelsdown,youcantype.

with(ball)y+=8;

Ifyouwanttoexecutemultiplestatements,putcurlybracketsaroundthem.Soforexample,tomoveallballstoarandomposition,youcanuse

with(ball)

{

Page 221: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

x=random(room_width);

y=random(room_height);

}

Notethat,withinthestatement(s),theindicatedinstancehasbecometheselfinstance.Withinthestatementstheoriginalselfinstancehasbecometheotherinstance.Soforexample,tomoveallballstothepositionofthecurrentinstance,youcantype

with(ball)

{

x=other.x;

y=other.y;

}

Useofthewithstatementisextremelypowerful.Letmegiveafewmoreexamples.Todestroyallballsyoutype

with(ball)instance_destroy();

Ifabombexplodesandyouwanttodestroyallinstancesclosebyyoucanuse

with(all)

{

if(distance_to_object(other)<50)instance_destroy();

}

Page 222: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Comment

Youcanaddcommenttoyourprograms.Everythingonalineafter//isnotread.Youcanalsomakeamulti-linecommentbyplacingthetextbetween/*and*/.(Colorcodingmightnotworkcorrectlyhere!PressF12tore-colorcodethetextifanerroroccurs.)

Page 223: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

FunctionsandvariablesinGML

GMLcontainsalargenumberofbuilt-infunctionsandvariables.Withtheseyoucancontrolanypartofthegame.Forallactionstherearecorrespondingfunctionssoyouactuallydon'tneedtouseanyactionsifyoupreferusingcode.Buttherearemanymorefunctionsandvariablesthatcontrolaspectsofthegamethatcannotbeusedwithactionsonly.Soifyouwanttomakeadvancedgamesyouarestronglyadvisedtoreadthroughthefollowingchapterstogetanoverviewofallthatispossible.Pleasenotethatthesevariablesandfunctionscanalsobeusedwhenprovidingvaluesforactions.Soevenifyoudon'tplanonusingcodeorwritingscripts,youwillstillbenefitfromthisinformation.

Thefollowingconventionisusedbelow.Variablenamesmarkedwitha*areread-only,thatis,theirvaluecannotbechanged.Variablenameswith[0..n]afterthemarearrays.Therangeofpossibleindicesisgiven.

Page 224: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Computingthings

GameMakercontainsalargenumberoffunctionstocomputecertainthings.Hereisacompletelist.

InformationontheGMLlanguagecanbefoundinthefollowingpages:

ConstantsReal-valuedfunctionsStringhandlingfunctionsDealingwithdatesandtime

Page 225: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Constants

Thefollowingmathematicalconstantsexist:

trueEqualto1.falseEqualto0.piEqualto3.1415...

Page 226: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Real-valuedfunctions

Thefollowingfunctionsexistthatdealwithrealnumbers.

random(x)Returnsarandomrealnumberbetween0andx.Thenumberisalwayssmallerthanx.random_range(x1,x2)Returnsarandomrealnumberbetweenx1(inclusive)andx2(exclusive).irandom(x)Returnsarandomintegernumberbetween0andx(inclusivewhenxisaninteger).irandom_range(x1,x2)Returnsarandomrealnumberbetweenx1(inclusive)andx2(inclusive).Bothx1andx2mustbeintegervalues(otherwisetheyareroundeddown).random_set_seed(seed)Setstheseed(aninteger)thatisusedfortherandomnumbergeneration.Canbeusedtorepeatthesamerandomsequence.(Notethoughthatalsosomeactionsandthesystemitselfusesrandomnumbers.)random_get_seed()Returnsthecurrentseed.randomize()Setstheseedtoarandomnumber.choose(val1,val2,val3,...)Returnsoneoftheargumentschoosenrandomly.Thefunctioncanhaveupto16arguments.abs(x)Returnstheabsolutevalueofx.sign(x)Returnsthesignofx(-1,0or1).round(x)Returnsxroundedtothenearestinteger.floor(x)Returnsthefloorofx,thatis,xroundeddowntoaninteger.ceil(x)Returnstheceilingofx,thatis,xroundeduptoaninteger.frac(x)Returnsthefractionalpartofx,thatis,thepartbehindthedecimaldot.sqrt(x)Returnsthesquarerootofx.xmustbenon-negative.sqr(x)Returnsx*x.power(x,n)Returnsxtothepowern.exp(x)Returnsetothepowerx.ln(x)Returnsthenaturallogarithmofx.log2(x)Returnsthelogbase2ofx.log10(x)Returnsthelogbase10ofx.

Page 227: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

logn(n,x)Returnsthelogbasenofx.sin(x)Returnsthesineofx(xinradians).cos(x)Returnsthecosineofx(xinradians).tan(x)Returnsthetangentofx(xinradians).arcsin(x)Returnstheinversesineofx.arccos(x)Returnstheinversecosineofx.arctan(x)Returnstheinversetangentofx.arctan2(y,x)Calculatesarctan(Y/X),andreturnsanangleinthecorrectquadrant.degtorad(x)Convertsdegreestoradians.radtodeg(x)Convertsradianstodegrees.min(val1,val2,val3,...)Returnstheminimumofthevalues.Thefunctioncanhaveupto16arguments.Theymusteitherbeallrealorallstrings.max(val1,val2,val3,...)Returnsthemaximumofthevalues.Thefunctioncanhaveupto16arguments.Theymusteitherbeallrealorallstrings.mean(val1,val2,val3,...)Returnstheaverageofthevalues.Thefunctioncanhaveupto16arguments.Theymustallberealvalues.median(val1,val2,val3,...)Returnsthemedianofthevalues,thatis,themiddlevalue.(Whenthenumberofargumentsiseven,thesmallerofthetwomiddlevaluesisreturned.)Thefunctioncanhaveupto16arguments.Theymustallberealvalues.point_distance(x1,y1,x2,y2)Returnsthedistancebetweenpoint(x1,y1)andpoint(x2,y2).point_direction(x1,y1,x2,y2)Returnsthedirectionfrompoint(x1,y1)towardpoint(x2,y2)indegrees.lengthdir_x(len,dir)Returnsthehorizontalx-componentofthevectordeterminedbytheindicatedlengthanddirection.lengthdir_y(len,dir)Returnstheverticaly-componentofthevectordeterminedbytheindicatedlengthanddirection.is_real(x)Returnswhetherxisarealvalue(asopposedtoastring).is_string(x)Returnswhetherxisastring(asopposedtoarealvalue).

Page 228: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 229: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Stringhandlingfunctions

Thefollowingfunctionsdealwithcharactersandstring.

chr(val)Returnsastringcontainingthecharacterwithascicodeval.ord(str)Returnstheascicodeofthefirstcharacterinstr.real(str)Turnsstrintoarealnumber.strcancontainaminussign,adecimaldotandevenanexponentialpart.string(val)Turnstherealvalueintoastringusingastandardformat(nodecimalplaceswhenitisaninteger,andtwodecimalplacesotherwise).string_format(val,tot,dec)Turnsvalintoastringusingyourownformat:totindicatesthetotalnumberofplacesanddecindicatesthenumberofdecimalplaces.string_length(str)Returnsthenumberofcharactersinthestring.string_pos(substr,str)Returnsthepositionofsubstrinstr(0=nooccurrence).string_copy(str,index,count)Returnsasubstringofstr,startingatpositionindex,andoflengthcount.string_char_at(str,index)Returnsthecharacterinstratpositionindex.string_delete(str,index,count)Returnsacopyofstrwiththepartremovedthatstartsatpositionindexandhaslengthcount.string_insert(substr,str,index)Returnsacopyofstrwithsubstraddedatpositionindex.string_replace(str,substr,newstr)Returnsacopyofstrwiththefirstoccurrenceofsubstrreplacedbynewstr.string_replace_all(str,substr,newstr)Returnsacopyofstrwithalloccurrencesofsubstrreplacedbynewstr.string_count(substr,str)Returnsthenumberofoccurrencesofsubstrinstr.string_lower(str)Returnsalowercasecopyofstr.string_upper(str)Returnsanuppercasecopyofstr.string_repeat(str,count)Returnsastringconsistingofcountcopiesofstr.

Page 230: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

string_letters(str)Returnsastringthatonlycontainsthelettersinstr.string_digits(str)Returnsastringthatonlycontainsthedigitsinstr.string_lettersdigits(str)Returnsastringthatcontainsthelettersanddigitsinstr.

Thefollowingfunctionsdealwiththeclipboardforstoringtext.

clipboard_has_text()Returnswhetherthereisanytextontheclipboard.clipboard_get_text()Returnsthecurrenttextontheclipboard.clipboard_set_text(str)Setsthestringstrontheclipboard.

Page 231: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Dealingwithdatesandtime

InGameMakerthereareanumberoffunctionstodealwithdatesandtime.Adate-timecombinationisstoredinarealnumber.Theintegralpartofadate-timevalueisthenumberofdaysthathavepassedsince12/30/1899.Thefractionalpartofthedate-timevalueisfractionofa24hourdaythathaselapsed.Thefollowingfunctionsexist:

date_current_datetime()Returnsthedate-timevaluethatcorrespondstothecurrentmoment.date_current_date()Returnsthedate-timevaluethatcorrespondstothecurrentdateonly(ignoringthetime).date_current_time()Returnsthedate-timevaluethatcorrespondstothecurrenttimeonly(ignoringthedate).date_create_datetime(year,month,day,hour,minute,second)Createsadate-timevaluecorrespondingtotheindicateddateandtime.date_create_date(year,month,day)Createsadate-timevaluecorrespondingtotheindicateddate.date_create_time(hour,minute,second)Createsadate-timevaluecorrespondingtotheindicatedtime.date_valid_datetime(year,month,day,hour,minute,second)Returnswhethertheindicateddateandtimearevalid.date_valid_date(year,month,day)Returnswhethertheindicateddateisvalid.date_valid_time(hour,minute,second)Returnswhethertheindicatedtimeisvalid.date_inc_year(date,amount)Returnsanewdatethatisamountyearsaftertheindicateddate.amountmustbeanintegernumber.date_inc_month(date,amount)Returnsanewdatethatisamountmonthsaftertheindicateddate.amountmustbeanintegernumber.date_inc_week(date,amount)Returnsanewdatethatisamountweeksaftertheindicateddate.amountmustbeanintegernumber.date_inc_day(date,amount)Returnsanewdatethatisamountdaysaftertheindicateddate.amountmustbeanintegernumber.date_inc_hour(date,amount)Returnsanewdatethatisamount

Page 232: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

hoursaftertheindicateddate.amountmustbeanintegernumber.date_inc_minute(date,amount)Returnsanewdatethatisamountminutesaftertheindicateddate.amountmustbeanintegernumber.date_inc_second(date,amount)Returnsanewdatethatisamountsecondsaftertheindicateddate.amountmustbeanintegernumber.date_get_year(date)Returnstheyearcorrespondingtothedate.date_get_month(date)Returnsthemonthcorrespondingtothedate.date_get_week(date)Returnstheweekoftheyearcorrespondingtothedate.date_get_day(date)Returnsthedayofthemonthcorrespondingtothedate.date_get_hour(date)Returnsthehourcorrespondingtothedate.date_get_minute(date)Returnstheminutecorrespondingtothedate.date_get_second(date)Returnsthesecondcorrespondingtothedate.date_get_weekday(date)Returnsthedayoftheweekcorrespondingtothedate.date_get_day_of_year(date)Returnsthedayoftheyearcorrespondingtothedate.date_get_hour_of_year(date)Returnsthehouroftheyearcorrespondingtothedate.date_get_minute_of_year(date)Returnstheminuteoftheyearcorrespondingtothedate.date_get_second_of_year(date)Returnsthesecondoftheyearcorrespondingtothedate.date_year_span(date1,date2)Returnsthenumberofyearsbetweenthetwodates.Itreportsincompleteyearsasafraction.date_month_span(date1,date2)Returnsthenumberofmonthsbetweenthetwodates.Itreportsincompletemonthsasafraction.date_week_span(date1,date2)Returnsthenumberofweeksbetweenthetwodates.Itreportsincompleteweeksasafraction.date_day_span(date1,date2)Returnsthenumberofdaysbetweenthetwodates.Itreportsincompletedaysasafraction.date_hour_span(date1,date2)Returnsthenumberofhoursbetweenthetwodates.Itreportsincompletehoursasafraction.date_minute_span(date1,date2)Returnsthenumberofminutes

Page 233: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

betweenthetwodates.Itreportsincompleteminutesasafraction.date_second_span(date1,date2)Returnsthenumberofsecondsbetweenthetwodates.Itreportsincompletesecondsasafraction.date_compare_datetime(date1,date2)Comparesthetwodate-timevalues.Returns-1,0,or1dependingonwhetherthefirstissmaller,equal,orlargerthanthesecondvalue.date_compare_date(date1,date2)Comparesthetwodate-timevaluesonlytakingthedatepartintoaccount.Returns-1,0,or1dependingonwhetherthefirstissmaller,equal,orlargerthanthesecondvalue.date_compare_time(date1,date2)Comparesthetwodate-timevaluesonlytakingthetimepartintoaccount.Returns-1,0,or1dependingonwhetherthefirstissmaller,equal,orlargerthanthesecondvalue.date_date_of(date)Returnsthedatepartoftheindicateddate-timevalue,settingthetimepartto0.date_time_of(date)Returnsthetimepartoftheindicateddate-timevalue,settingthedatepartto0.date_datetime_string(date)Returnsastringindicatingthegivendateandtimeinthedefaultformatforthesystem.date_date_string(date)Returnsastringindicatingthegivendateinthedefaultformatforthesystem.date_time_string(date)Returnsastringindicatingthegiventimeinthedefaultformatforthesystem.date_days_in_month(date)Returnsthenumberofdaysinthemonthindicatedbythedate-timevalue.date_days_in_year(date)Returnsthenumberofdaysintheyearindicatedbythedate-timevalue.date_leap_year(date)Returnswhethertheyearindicatedbythedate-timevalueisaleapyear.date_is_today(date)Returnswhethertheindicateddate-timevalueisontoday.

Page 234: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Gameplay

Therearealargenumberofvariablesandfunctionsthatyoucanusetodefinethegameplay.Theseinparticularinfluencethemovementandcreationofinstances,thetiming,theroom,andthehandlingofevents.

Informationongameplaycanbefoundinthefollowingpages:

MovingAroundPathsMotionPlanningCollisionDetectionInstancesDeactivatingInstancesTimingRoomsScoreGeneratingEventsMiscellaneousVariablesandFunctions

Page 235: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Movingaround

Obviously,animportantaspectofgamesisthemovingaroundofobjectinstances.Eachinstancehastwobuilt-invariablesxandythatindicatethepositionoftheinstance.(Tobeprecise,theyindicatetheplacewheretheoriginofthespriteisplaced.Position(0,0)isthetop-leftcorneroftheroom.Youcanchangethepositionoftheinstancebychangingitsxandyvariables.Ifyouwanttheobjecttomakecomplicatedmotionsthisisthewaytogo.Youtypicallyputthiscodeinthestepeventfortheobject.

Iftheobjectmoveswithconstantspeedanddirection,thereisaneasierwaytodothis.Eachobjectinstancehasahorizontalspeed(hspeed)andaverticalspeed(vspeed).Bothareindicatedinpixelsperstep.Apositivehorizontalspeedmeansamotiontotheright,anegativehorizontalspeedmeanamotiontotheleft.Positiveverticalspeedisdownwardsandnegativeverticalspeedisupwards.Soyouhavetosetthesevariablesonlyonce(forexampleinthecreatingevent)togivetheobjectinstanceaconstantmotion.

Thereisquiteadifferentwayforspecifyingmotion,usingadirection(indegrees0-359),andaspeed(shouldbenon-negative).Youcansetandreadthesevariablestospecifyanarbitrarymotion.(Internallythisischangedintovaluesforhspeedandvspeed.)Alsothereisthefrictionandthegravityandgravitydirection.Finally,thereisthefunctionmotion_add(dir,speed)toaddamotiontothecurrentone.

Tobecomplete,eachinstancehasthefollowingvariablesandfunctionsdealingwithitspositionandmotion:

xItsx-position.yItsy-position.xpreviousItspreviousx-position.ypreviousItspreviousy-position.xstartItsstartingx-positionintheroom.ystartItsstartingy-positionintheroom.hspeedHorizontalcomponentofthespeed.

Page 236: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

vspeedVerticalcomponentofthespeed.directionItscurrentdirection(0-360,counter-clockwise,0=totheright).speedItscurrentspeed(pixelsperstep).frictionCurrentfriction(pixelsperstep).gravityCurrentamountofgravity(pixelsperstep).gravity_directionDirectionofgravity(270isdownwards).motion_set(dir,speed)Setsthemotionwiththegivenspeedindirectiondir.motion_add(dir,speed)Addsthemotiontothecurrentmotion(asavectoraddition).

Therearealargenumberoffunctionsavailablethathelpyouindefiningyourmotions:

place_free(x,y)Returnswhethertheinstanceplacedatposition(x,y)iscollision-free.Thisistypicallyusedasacheckbeforeactuallymovingtothenewposition.place_empty(x,y)Returnswhethertheinstanceplacedatposition(x,y)meetsnobody.Sothisfunctiontakesalsonon-solidinstancesintoaccount.place_meeting(x,y,obj)Returnswhethertheinstanceplacedatposition(x,y)meetsobj.objcanbeanobjectinwhichcasethefunctionreturnstrueissomeinstanceofthatobjectismet.Itcanalsobeaninstanceid,thespecialwordallmeaninganinstanceofanyobject,orthespecialwordother.place_snapped(hsnap,vsnap)Returnswhethertheinstanceisalignedwiththesnappingvalues.move_random(hsnap,vsnap)Movestheinstancetoafreerandom,snappedposition,likethecorrespondingaction.move_snap(hsnap,vsnap)Snapstheinstance,likethecorrespondingaction.move_wrap(hor,vert,margin)Wrapstheinstancewhenithaslefttheroomtotheotherside.horindicateswhethertowraphorizontalyandvertindicateswhethertowrapvertically.marginindicateshowfartheoriginoftheinstancemustbeoutsidetheroombeforethewraphappens.Soitisamarginaroundtheroom.Youtypicallyusethis

Page 237: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

functionintheOutsideevent.move_towards_point(x,y,sp)Movestheinstanceswithspeedsptowardposition(x,y).move_bounce_solid(adv)Bouncesagainstsolidinstances,likethecorrespondingaction.advindicateswhethertouseadvancebounce,thatalsotakesslantedwallsintoaccount.move_bounce_all(adv)Bouncesagainstallinstances,insteadofjustthesolidones.move_contact_solid(dir,maxdist)Movestheinstanceinthedirectionuntilacontactpositionwithasolidobjectisreached.Ifthereisnocollisionatthecurrentposition,theinstanceisplacedjustbeforeacollisionoccurs.Iftherealreadyisacollisiontheinstanceisnotmoved.Youcanspecifythemaximaldistancetomove(useanegativenumberforanarbitrarydistance).move_contact_all(dir,maxdist)Sameasthepreviousfunctionbutthistimeyoustopatacontactwithanyobject,notjustsolidobjects.move_outside_solid(dir,maxdist)Movestheinstanceinthedirectionuntilitnolongerlieswithinasolidobject.Ifthereisnocollisionatthecurrentpositiontheinstanceisnotmoved.Youcanspecifythemaximaldistancetomove(useanegativenumberforanarbitrarydistance).move_outside_all(dir,maxdist)Sameasthepreviousfunctionbutthistimeyoumoveuntiloutsideanyobject,notjustsolidobjects.distance_to_point(x,y)Returnsthedistanceoftheboundingboxofthecurrentinstanceto(x,y).(Iftheinstancedoesnothaveaspriteormask,theresultofthefunctionisundefined.)distance_to_object(obj)Returnsthedistanceoftheinstancetothenearestinstanceofobjectobj.(Iftheinstanceorobjectdoesnothaveaspriteormask,theresultofthefunctionisundefined.)position_empty(x,y)Returnswhetherthereisnothingatposition(x,y).position_meeting(x,y,obj)Returnswhetheratposition(x,y)thereisaninstanceobj.objcanbeanobject,aninstanceid,orthekeywordsself,other,orall.

Page 238: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 239: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Paths

InGameMakeryoucandefinepathsandorderinstancestofollowsuchpaths.Althoughyoucanuseactionsforthis,therearefunctionsandvariablesthatgiveyoumoreflexibility:

path_start(path,speed,endaction,absolute)Startsapathforthecurrentinstance.Thepathisthenameofthepathyouwanttostart.Thespeedisthespeedwithwhichthepathmustbefollowed.Anegativespeedmeansthattheinstancemovesbackwardsalongthepath.Theendactionindicateswhatshouldhappenwhentheendofthepathisreached.Thefollowingvaluescanbeused:

0:stopthepath1:continuefromthestartposition(ifthepathisnotclosedwejumptothestartposition2:continuefromthecurrentposition3:reversethepath,thatischangethesignofthespeed

Theargumentabsoluteshouldbetrueorfalse.Whentruetheabsolutecoordinatesofthepathareused.Whenfalsethepathisrelativetothecurrentpositionoftheinstance.Tobemoreprecise,ifthespeedispositive,thestartpointofthepathwillbeplacedonthecurrentpositionandthepathisfollowedfromthere.Whenthespeedisnegativetheendpointofthepathwillbeplacedonthecurrentpositionandthepathisfollowedbackwardsfromthere.path_end()Endsthefollowingofapathforthecurrentinstance.path_index*Indexofthecurrentpaththeinstancefollows.Youcannotchangethisdirectlybutmustusethefunctionabove.path_positionPositioninthecurrentpath.0isthebeginningofthepath.1istheendofthepath.Thevaluemustliebetween0and1.path_positionpreviousPreviouspositioninthecurrentpath.Thiscanbeusede.g.incollisioneventstosetthepositiononthepathbacktothepreviousposition.path_speedSpeed(inpixelsperstep)withwhichthepathmustbefollowed.Useanegativespeedtomovebackwards.

Page 240: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

path_orientationOrientation(counter-clockwise)intowhichthepathisperformed.0isthenormalorientationofthepath.path_scaleScaleofthepath.Increasetomakethepathlarger.1isthedefaultvalue.path_endactionTheactionthatmustbeperformedattheendofthepath.Youcanusethevaluesindicatedabove.

Page 241: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Motionplanning

Motionplanninghelpsyoutomovecertaininstancesfromagivenlocationtoadifferentlocationwhileavoidingcollisionswithcertainotherinstances(e.g.walls).Motionplanningisadifficultproblem.Itisimpossibletogivegeneralfunctionsthatwillworkproperlyinallsituations.Also,computingcollisionfreemotionsisatime-consumingoperation.Soyouhavebecarefulhowandwhenyouapplyit.Pleasekeeptheseremarksinmindwhenyouuseanyofthefollowingfunctions.

DifferentformsofmotionplanningareprovidedbyGameMaker.Thesimplestformletsaninstancetakeasteptowardsaparticulargoalposition,tryingtogostraightifpossiblebuttakingadifferentdirectionifrequired.Thesefunctionsshouldbeusedinthestepeventofaninstance.Theycorrespondtothemotionplanningactionsthatarealsoavailable:

mp_linear_step(x,y,stepsize,checkall)Thisfunctionletstheinstancetakeastepstraighttowardstheindicatedposition(x,y).Thesizeofthestepisindicatedbythestepsize.Iftheinstanceisalreadyatthepositionitwillnotmoveanyfurther.Ifcheckallistruetheinstancewillstopwhenithitsaninstanceofanyobject.Ifitisfalseitonlystopswhenhittingasolidinstance.Notethatthisfunctiondoesnottrytomakedetoursifitmeetsanobstacle.Itsimplyfailsinthatcase.Thefunctionreturnswhetherornotthegoalpositionwasreached.mp_linear_step_object(x,y,stepsize,obj)Sameasthefunctionabovebutthistimeonlyinstancesofobjareconsideredasobstacles.objcanbeanobjectoraninstanceid.mp_potential_step(x,y,stepsize,checkall)Likethepreviousfunction,thisfunctionletstheinstancetakeasteptowardsaparticularposition.Butinthiscaseittriestoavoidobstacles.Whentheinstancewouldrunintoasolidinstance(oranyinstancewhencheckallistrue)itwillchangethedirectionofmotiontotrytoavoidtheinstanceandmovearoundit.Theapproachisnotguaranteedto

Page 242: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

workbutinmosteasycasesitwilleffectivelymovetheinstancetowardsthegoal.Thefunctionreturnswhetherornotthegoalwasreached.mp_potential_step_object(x,y,stepsize,obj)Sameasthefunctionabovebutthistimeonlyinstancesofobjareconsideredasobstacles.objcanbeanobjectoraninstanceid.mp_potential_settings(maxrot,rotstep,ahead,onspot)Thepreviousfunctiondoesitsworkusinganumberofparametersthatcanbechangedusingthisfunction.Globallythemethodworksasfollows.Itfirsttriestomovestraighttowardsthegoal.Itlooksanumberofstepsaheadwhichcanbesetwiththeparameterahead(default3).Reducingthisvaluemeansthattheinstancewillstartchangingdirectionlater.Increasingitmeansitwillstartchangingdirectionearlier.Ifthischeckleadstoacollisionitstartslookingatdirectionsmoretotheleftandtotherightofthebestdirection.Itdoesthisinstepsofsizerotstep(default10).Reducingthisgivestheinstancemoremovementpossibilitiesbutwillbeslower.Theparametermaxrotisabitmoredifficulttoexplain.Theinstancehasacurrentdirection.maxrot(default30)indicateshowmuchitisallowedtochangeitscurrentdirectioninastep.Soevenifitcanmovee.g.straighttothegoalitwillonlydosoifitdoesnotviolatethismaximalchangeofdirection.Ifyoumakemaxrotlargetheinstancecanchangealotineachstep.Thiswillmakeiteasiertofindashortpathbutthepathwillbeuglier.Ifyoumakethevaluesmallerthepathwillbesmootherbutitmighttakelongerdetours(andsometimesevenfailtofindthegoal).Whennostepcanbemadethebehaviordependsonthevalueoftheparameteronspot.Ifonspotistrue(thedefaultvalue),theinstancewillrotateonitsspotbytheamountindicatedwithmaxrot.Ifitisfalseitwillnotmoveatall.Settingittofalseisusefulfore.g.carsbutreducesthechanceoffindingapath.

Pleasenotethatthepotentialapproachusesonlylocalinformation.Soitwillonlyfindapathifthislocalinformationisenoughtodeterminetherightdirectionofmotion.Forexample,itwillfailtofindapathoutofamaze(mostofthetime).

Thesecondkindoffunctionscomputesacollision-freepathforthe

Page 243: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

instance.Oncethispathhasbeencomputedyoucanassignittotheinstancetomovetowardsthegoal.Thecomputationofthepathwilltakesometimebutafterthattheexecutionofthepathwillbefast.Ofcoursethisisonlyvalidifthesituationhasnotchangedinthemeantime.Forexample,ifobstacleschangeyoupossiblywillneedtorecomputethepath.Againnoticethatthesefunctionsmightfail.ThesefunctionsareonlyavailableintheProEditionofGameMaker.

Thefirsttwofunctionsusethelinearmotionandpotentialfieldapproachthatwerealsousedforthestepfunctions.

mp_linear_path(path,xg,yg,stepsize,checkall)Thisfunctioncomputesastraight-linepathfortheinstancefromitscurrentpositiontotheposition(xg,yg)usingtheindicatedstepsize.Itusesstepsasinthefunctionmp_linear_step().Theindicatedpathmustalreadyexistandwillbeoverwrittenbythenewpath.(Seealaterchapteronhowtocreateanddestroypaths.)Thefunctionwillreturnwhetherapathwasfound.Thefunctionwillstopandreportfailureifnostraightpathexistsbetweenstartandgoal.Ifitfailsapathisstillcreatedthatrunstillthepositionwheretheinstancewasblocked.mp_linear_path_object(path,xg,yg,stepsize,obj)Sameasthefunctionabovebutthistimeonlyinstancesofobjareconsideredasobstacles.objcanbeanobjectoraninstanceid.mp_potential_path(path,xg,yg,stepsize,factor,checkall)Thisfunctioncomputesapathfortheinstancefromitscurrentpositionandorientationtotheposition(xg,yg)usingtheindicatedstepsizetryingtoavoidcollisionwithobstacles.Itusespotentialfieldsteps,likeinthefunctionmp_potential_step()andalsotheparametersthatcanbesetwithmp_potential_settings().Theindicatedpathmustalreadyexistandwillbeoverwrittenbythenewpath.(Seealaterchapteronhowtocreateanddestroypaths.)Thefunctionwillreturnwhetherapathwasfound.Toavoidthefunctioncontinuingtocomputeforeveryouneedtoprovidealengthfactorlargerthan1.Thefunctionwillstopandreportfailureifitcannotfindapathshorterthanthisfactortimesthedistancebetweenstartandgoal.Afactorof4isnormallygoodenoughbutifyouexpectlongdetoursyoumightmakeitlonger.Ifitfailsapathisstillcreatedthatrunsinthedirection

Page 244: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ofthegoalbutitwillnotreachit.mp_potential_path_object(path,xg,yg,stepsize,factor,obj)Sameasthefunctionabovebutthistimeonlyinstancesofobjareconsideredasobstacles.objcanbeanobjectoraninstanceid.

Theotherfunctionsuseamuchmorecomplexmechanismusingagrid-basedapproach(sometimescalledanA*algorithm).Itwillbemoresuccessfulinfindingpaths(althoughitstillmightfail)andwillfindshorterpathsbutitrequiredmoreworkonyourside.Theglobalideaisasfollows.Firstofallweputagridon(therelevantpartof)theroom.Youcanchoosetouseafinegrid(whichwillbeslower)oracoarsegrid.Next,forallrelevantobjectswedeterminethegridcellstheyoverlap(eitherusingboundingboxesorprecisechecking)andmarkthesecellsasbeingforbidden.Soacellwillbemarkedtotallyforbidden,evenifitonlypartiallyoverlapswithanobstacle.Finallywespecifyastartandagoalposition(whichmustlieinfreecells)andthefunctioncomputestheshortestpath(actuallyclosetotheshortest)betweenthese.Thepathwillrunbetweencentersoffreecells.Soifthecellsarelargeenoughsothattheinstanceplacedatitscenterwillliecompletelyinsideitthiswillbesuccessful.Thispathyoucannowgivetoaninstancetofollow.

Thegrid-basedapproachisverypowerful(andisusedinmanyprofessionalgames)butitrequiresthatyoudosomecarefulthinking.Youmustdeterminewhichareaandcellsizearegoodenoughforsolvingthegame.Alsoyoumustdeterminewhichobjectsmustbeavoidedandwhetherprecisecheckingisimportant.Alltheseparametersstronglyinfluencetheefficiencyoftheapproach.

Inparticularthesizeofthecellsiscrucial.Rememberthatthecellsmustbelargeenoughsothatthemovingobjectplacedwithitsoriginonthecenterofacellmustliecompletelyinsidethecell.(Becarefulaboutthepositionoftheoriginoftheobject.Alsorealizethatyoucanshiftthepathiftheoriginoftheobjectisnotinitscenter!)Ontheotherhand,thesmallerthecellsthemorepossiblepathsexist.Ifyoumakecellstoolarge,openingsbetweenobstaclesmaygetclosedbecauseallcellsintersectanobstacle.

Theactualfunctionsforthegrid-basedapproachareasfollows:

Page 245: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

mp_grid_create(left,top,hcells,vcells,cellwidth,cellheight)Thisfunctioncreatesthegrid.Itreturnsanindexthatmustbeusedinallothercalls.Youcancreateandmaintainmultiplegridstructuresatthesamemoment.leftandtopindicatethepositionofthetop-leftcornerofthegrid.hcellsandvcellsindicatethenumberofhorizontalandverticalcells.Finallycellwidthandcellheightindicatethesizeofthecells.mp_grid_destroy(id)Destroystheindicatedgridstructureandfreesitsmemory.Don'tforgettocallthisifyoudon'tneedthestructureanymore.mp_grid_clear_all(id)Markallcellsinthegridtobefree.mp_grid_clear_cell(id,h,v)Clearstheindicatedcell.Cell0,0isthetopleftcell.mp_grid_clear_rectangle(id,left,top,right,bottom)Clearsallcellsthatintersecttheindicatedrectangle(inroomcoordinates).mp_grid_add_cell(id,h,v)Markstheindicatedcellasbeingforbidden.Cell0,0isthetopleftcell.mp_grid_add_rectangle(id,left,top,right,bottom)Marksallcellsthatintersecttheindicatedrectangleasbeingforbidden.mp_grid_add_instances(id,obj,prec)Marksallcellsthatintersectaninstanceoftheindicatedobjectasbeingforbidden.Youcanalsouseanindividualinstancebymakingobjtheidoftheinstance.Alsoyoucanusethekeywordalltoindicateallinstancesofallobjects.precindicateswhetherprecisecollisioncheckingmustbeused(willonlyworkifprecisecheckingisenabledforthespriteusedbytheinstance).mp_grid_path(id,path,xstart,ystart,xgoal,ygoal,allowdiag)

Computesapaththroughthegrid.pathmustindicateanexistingpaththatwillbereplacedbythecomputerpath.xstartandystartindicatethestartofthepathandxgoalandygoalthegoal.allowdiagindicateswhetherdiagonalmovesareallowedinsteadofjusthorizontalorvertical.Thefunctionreturnswhetheritsucceededinfindingapath.(Notethatthepathisindependentofthecurrentinstance;Itisapaththroughthegrid,notapathforaspecificinstance.)mp_grid_draw(id)Thisfunctiondrawsthegridwithgreencellsbeingfreeandredcellsbeingforbidden.Thisfunctionisslowandonly

Page 246: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

providedasadebugtool.

Page 247: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Collisionchecking

Whenplanningmotionsordecidingoncertainactions,itisoftenimportanttoseewhethertherearecollisionswithotherobjectsatcertainplaces.Thefollowingroutinescanbeusedforthis.Allthesehavethreeargumentsincommon:Theargumentobjcanbeanobject,thekeywordall,ortheidofaninstance.Theargumentprecindicateswhetherthecheckshouldbepreciseoronlybasedontheboundingboxoftheinstance.Precisecheckingisonlydonewhenthespritefortheinstancehastheprecisecollisioncheckingset.Theargumentnotmecanbesettotruetoindicatethatthecallinginstanceshouldnotbechecked.Allthesefunctionsreturneithertheidofoneoftheinstancesthatcollide,ortheyreturnanegativevaluewhenthereisnocollision.

collision_point(x,y,obj,prec,notme)Thisfunctiontestswhetheratpoint(x,y)thereisacollisionwithentitiesofobjectobj.collision_rectangle(x1,y1,x2,y2,obj,prec,notme)Thisfunctiontestswhetherthereisacollisionbetweenthe(filled)rectanglewiththeindicatedoppositecornersandentitiesofobjectobj.Forexample,youcanusethistotestwhetheranareaisfreeofobstacles.collision_circle(xc,yc,radius,obj,prec,notme)Thisfunctiontestswhetherthereisacollisionbetweenthe(filled)circlecenteredatposition(xc,yc)withthegivenradiusandentitiesofobjectobj.Forexample,youcanusethistotestwhetherthereisanobjectclosetoaparticularlocation.collision_ellipse(x1,y1,x2,y2,obj,prec,notme)Thisfunctiontestswhetherthereisacollisionbetweenthe(filled)ellipsewiththeindicatedoppositecornersandentitiesofobjectobj.collision_line(x1,y1,x2,y2,obj,prec,notme)Thisfunctiontestswhetherthereisacollisionbetweenthelinesegmentfrom(x1,y1)to(x2,y2)andentitiesofobjectobj.Thisisapowerfulfunction.Youcane.g.useittotestwhetheraninstancecanseeanotherinstancebycheckingwhetherthelinesegmentbetweenthemintersectsawall.

Page 248: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 249: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Instances

Inthegame,thebasicunitsaretheinstancesofthedifferentobjects.Duringgameplayyoucanchangeanumberofaspectsoftheseinstances.Alsoyoucancreatenewinstancesanddestroyinstances.Besidesthemovementrelatedvariablesdiscussedaboveandthedrawingrelatedvariablesdiscussedbelow,eachinstancehasthefollowingvariables:

object_index*Indexoftheobjectthisisaninstanceof.Thisvariablecannotbechanged.id*Theuniqueidentifierfortheinstance(>=100000).(Notethatwhendefiningroomstheidoftheinstanceunderthemouseisalwaysindicated.)mask_indexIndexofthespriteusedasmaskforcollisions.Givethisavalueof-1tomakeitthesameasthesprite_index.solidWhethertheinstanceissolid.Thiscanbechangedduringthegame.persistentWhethertheinstanceispersistentandwillreappearwhenmovingtoanotherroom.Youoftenwanttoswitchpersistenceoffatcertainmoments.(Forexampleifyougobacktothefirstroom.)

Thereisoneproblemwhendealingwithinstances.Itisnotsoeasytoidentifyindividualinstances.Theydon'thaveaname.Whenthereisonlyoneinstanceofaparticularobjectyoucanusetheobjectnamebutotherwiseyouneedtogettheidoftheinstance.Thisisauniqueidentifierfortheinstance.youcanuseitinwithstatementsandasobjectidentifier.Fortunatelythereareanumberofvariablesandroutinesthathelpyoulocateinstanceid's.

instance_count*Numberofinstancesthatcurrentlyexistintheroom.instance_id[0..n-1]*Theidoftheparticularinstance.Herenisthenumberofinstance.

Page 250: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Notethattheassignmentoftheinstancestotheinstanceid'schangeseverystepsoyoucannotusevaluesfromprevioussteps.Alsopleasenotethatinstancesthataredeletedwillremaininthelistuntiltheendofthestep.Soifyouarealsodeletinginstancesyouneedtocheckwhethertheinstancestillexists.Letmegiveanexample.Assumeeachunitinyourgamehasaparticularpowerandyouwanttolocatethestrongestone,youcouldusethefollowingcode:

{

maxid=-1;

maxpower=0;

for(i=0;i<instance_count;i+=1)

{

iii=instance_id[i];

if(instance_exists(iii))

if(iii.object_index==unit)

{

if(iii.power>maxpower)

{maxid=iii;maxpower=iii.power;}

}

}

}

Aftertheloopmaxidwillcontaintheidoftheunitwithlargestpower.Ofcourse,forthisparticularsituationthefollowingcodewouldbebetter:

{

maxid=-1;

maxpower=0;

with(unit)do

{

if(power>maxpower)

{maxid=self;maxpower=power;}

}

}

instance_find(obj,n)Returnstheidofthe(n+1)'thinstanceoftypeobj.objcanbeanobjectorthekeywordall.Ifitdoesnotexist,thespecialobjectnooneisreturned.Notethattheassignmentoftheinstancestotheinstanceid'schangeseverystepsoyoucannotusevaluesfromprevioussteps.

Page 251: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

instance_exists(obj)Returnswhetheraninstanceoftypeobjexists.objcanbeanobject,aninstanceid,orthekeywordall.instance_number(obj)Returnsthenumberofinstancesoftypeobj.objcanbeanobjectorthekeywordall.instance_position(x,y,obj)Returnstheidoftheinstanceoftypeobjatposition(x,y).Whenmultipleinstancesareatthatpositionthefirstisreturned.objcanbeanobjectorthekeywordall.Ifitdoesnotexist,thespecialobjectnooneisreturned.instance_nearest(x,y,obj)Returnstheidoftheinstanceoftypeobjnearestto(x,y).objcanbeanobjectorthekeywordall.instance_furthest(x,y,obj)Returnstheidoftheinstanceoftypeobjfurthestawayfrom(x,y).objcanbeanobjectorthekeywordall.instance_place(x,y,obj)Returnstheidoftheinstanceoftypeobjmetwhenthecurrentinstanceisplacedatposition(x,y).objcanbeanobjectorthekeywordall.Ifitdoesnotexist,thespecialobjectnooneisreturned.

Thefollowingfunctionscanbeusedforcreatinganddestroyinginstances.

instance_create(x,y,obj)Createsaninstanceofobjatposition(x,y).Thefunctionreturnstheidofthenewinstance.instance_copy(performevent)Createsacopyofthecurrentinstance.Theargumentindicateswhetherthecreationeventmustbeexecutedforthecopy.Thefunctionreturnstheidofthenewcopy.instance_destroy()Destroysthecurrentinstance.instance_change(obj,perf)Changestheinstanceintoobj.perfindicateswhethertoperformthedestroyandcreationevents.position_destroy(x,y)Destroysallinstanceswhosespritecontainsposition(x,y).position_change(x,y,obj,perf)Changesallinstancesat(x,y)intoobj.perfindicateswhethertoperformthedestroyandcreationevents.

Page 252: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 253: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Deactivatinginstances

Pleasebeawarethatdeactivatingandactivatinginstancescansometimesleadtounexpectedproblems.Soyouarestronglyadvisednottousethisfeatureexceptforverysimplesituationliketheonesdescribedbelow.Thefeatureismainlyleftinforbackwardcompatibility.

Whenyoucreatelargeroom,forexampleinplatformgames,withasmallview,manyinstanceslieoutsidetheview.Suchinstancesthougharestillactiveandwillexecutetheirevents.Alsowhenperformingcollisioncheckstheseinstancesaretakenintoaccount.Thiscancostalotoftime,whichisoftennotnecessary.(Forexample,oftenitisnotimportantwhetherinstancesoutsidetheviewmove.)TosolvethisproblemGameMakercontainssomefunctionstodeactivateandactivateinstances.Beforeusingthemyoumustthoughclearlyunderstandhowtheywork.

Whenyoudeactivateinstancestheyareinsomesenseremovedfromthegame.Theyarenotvisibleanymorenorareanyeventsexecutedforthem.Soforallactionsandfunctionstheydon'texistanymore.Thissavesalotoftimebutyouhavetobecareful.Forexample,whenyoudeleteallinstancesofaparticulartype,deactivatedinstancesarenotdeleted(becausetheydon'texist).Sodon'tthinkthatakeyaplayerpicksupcanunlockadeactivateddoor.Alsopersistentdeactivatedinstancesarenotmovedovertothenextroom(eventhoughtheyarepersistent).Alsomakesurethatafteryoudeactivateaninstancethatyounolongerexecutecodeforit.Thiscaninparticularhappenwhenaninstancedeactivatesitself.Ingeneralyoubetterneverhaveaninstancedeactivateitself.

Themostcrucialmistakeyoucanmakeistodeactivatetheinstancethatisresponsiblefortheactivation.Toavoidthissomeoftheroutinesbelowallowyoutoinsistthatthecallinginstanceshouldnotbedeactivateditself.

Herearetheavailableroutines:

Page 254: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

instance_deactivate_all(notme)Deactivatesallinstancesintheroom.Ifnotmeistruethecallinginstanceisnotdeactivated(whichisnormallywhatyouwant).instance_deactivate_object(obj)Deactivatesallinstancesintheroomofthegivenobject.Youcanalsousealltoindicatethatallinstancesmustbedeactivatedortheidofaninstancetodeactivateanindividualinstance.instance_deactivate_region(left,top,width,height,inside,notme)

Deactivatesallinstancesintheindicatedregion(thatis,thosewhoseboundingboxliespartiallyinsidetheregion).Ifinsideisfalsetheinstancescompletelyoutsidetheregionaredeactivated.Ifnotmeistruethecallinginstanceisnotdeactivated(whichisnormallywhatyouwant).instance_activate_all()Activatesallinstancesintheroom.instance_activate_object(obj)Activatesallinstancesintheroomofthegivenobject.Youcanalsousealltoindicatethatallinstancesmustbeactivatedortheidofaninstancetoactivateanindividualinstance.instance_activate_region(left,top,width,height,inside)Activatesallinstancesintheindicatedregion.Ifinsideisfalsetheinstancescompletelyoutsidetheregionareactivated.

Forexample,todeactivateallinstancesoutsidetheviewandactivatetheonesinsidetheview,youcouldplacethefollowingcodeinthestepeventofthemovingcharacter:

{

instance_activate_all();

instance_deactivate_region(view_xview[0],view_yview[0],

view_wview[0],view_hview[0],false,true);

}

Inpracticeyoumightwanttousearegionslightlylargerthantheview.

Page 255: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Timing

Goodgamesrequirecarefultimingofthingshappening.FortunatelyGameMakerdoesmostofthetimingforyou.Itmakessurethingshappenataconstantrate.Thisrateisdefinedwhendefiningtherooms.Butyoucanchangeitusingtheglobalvariableroom_speed.Soforexample,youcanslowlyincreasethespeedofthegame,makingitmoredifficult,byaddingaverysmallamount(like0.001)toroom_speedineverystep.Ifyourmachineisslowthegamespeedmightnotbeachieved.Thiscanbecheckedusingthevariablefpsthatconstantlymonitorstheactualnumberofframespersecond.Finally,forsomeadvancedtimingyoucanusethevariablecurrent_timethatgivesthenumberofmillisecondssincethecomputerwasstarted.Hereisthetotalcollectionofvariablesavailable(onlythefirstonecanbechanged):

room_speedSpeedofthegameinthecurrentroom(instepspersecond).fps*Numberofframesthatareactuallydrawnpersecond.current_time*Numberofmillisecondsthathavepassedsincethesystemwasstarted.current_year*Thecurrentyear.current_month*Thecurrentmonth.current_day*Thecurrentday.current_weekday*Thecurrentdayoftheweek(1=sunday,...,7=saturday).current_hour*Thecurrenthour.current_minute*Thecurrentminute.current_second*Thecurrentsecond.

Sometimesyoumightwanttostopthegameforashortwhile.Forthis,usethesleepfunction.

sleep(numb)Sleepsnumbmilliseconds.

Asyoushouldknow,everyinstancehas12differentalarmclocksthatyoucanset.Tochangethevalues(orgetthevalues)ofthedifferent

Page 256: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

alarmclocksusethefollowingvariable:

alarm[0..11]Valueoftheindicatedalarmclock.(Notethatalarmclocksonlygetupdatedwhenthealarmeventfortheobjectcontainsactions!)

Wehaveseenthatforcomplextimingissuesyoucanusethetimelineresource.Eachinstancecanhaveatimelineresourceassociatedwithit.Thefollowingvariablesdealwiththis:

timeline_indexIndexofthetimelineassociatedwiththeinstance.Youcansetthistoaparticulartimelinetousethatone.Setitto-1tostopusingatimelinefortheinstance.Notethatthisdoesnotstartthetimeline.Forthisusethevariabletimeline_running.timeline_positionCurrentpositionwithinthetimeline.Youcanchangethistoskipcertainpartsortorepeatparts.timeline_speedNormally,ineachstepthepositioninthetimelineisincreasedby1.Youcanchangethisamountbysettingthisvariabletoadifferentvalue.Youcanuserealnumberslike0.5.Ifthevalueislargerthanone,severalmomentscanhappenwithinthesametimestep.Theywillallbeperformedinthecorrectorder,sonoactionswillbeskipped.Youcanalsouseanegativevaluetoletthetimelineplaybackwards.timeline_runningIndicateswhetherthetimelineisrunning(true)orpausedorstopped(false).Youcanchangethisvariabletorunorstopthetimeline.timeline_loopingIndicatedwhetherthetimelineislooping(true)ornot(false).Youcanchangethisvariabletoswitchloopingonoroff.

Page 257: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Rooms

Gamesworkinrooms.Eachroomhasanindexthatisindicatedbythenameoftheroom.Thecurrentroomisstoredinvariableroom.Youcannotassumethatroomsarenumberedinaconsecutiveorder.Soneveraddorsubtractanumberfromtheroomvariable.Insteadusethefunctionsandvariablesindicatedbelow.Soatypicalpieceofcodeyouwilluseis:

{

if(room!=room_last)

{

room_goto_next();

}

else

{

game_end();

}

}

Thefollowingvariablesandfunctionsexistthatdealwithrooms.

roomIndexofthecurrentroom;canbechangedtogotoadifferentroom,butyouhadbetterusetheroutinesbelow.room_first*Indexofthefirstroominthegame.room_last*Indexofthelastroominthegame.room_goto(numb)Gototheroomwithindexnumb.room_goto_previous()Gotothepreviousroom.room_goto_next()Gotothenextroom.room_restart()Restartthecurrentroom.room_previous(numb)Returntheindexoftheroombeforenumb(-1=none)butdon'tgothere.room_next(numb)Returntheindexoftheroomafternumb(-1=none).game_end()Endthegame.game_restart()Restartthegame.

Page 258: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Whencallingoneoftheabovefunctionstochangetheroomorendorrestartthegame,pleaserealizethatthischangedoesactuallynotoccuratthatprecisemoment.Itonlyhappensafterthecurrentactionisfullyexecuted.Sotherestofthescriptwillstillbeexecuted,andthesameappliestopossiblecallingscripts.However,noeventsareexecutedanymore.Asthiscanleadtounexpectedbehavioryouarestronglyadvisednottoputanycodeanymoreaftertheuseofsuchfunctions.

Roomshaveanumberofadditionalproperties:

room_width*Widthoftheroominpixels.room_height*Heightoftheroominpixels.room_captionCaptionstringfortheroomthatisdisplayedinthecaptionofthewindow.room_persistentWhetherthecurrentroomispersistent.

Manygamesoffertheplayerthepossibilityofsavingthegameandloadingasavedgame.InGameMakerthishappensautomaticallywhentheplayerpress<F5>forsavingand<F6>forloading.Youcanalsosaveandloadgamesfromwithinapieceofcode(notethatloadingonlytakesplaceattheendofthecurrentstep).

game_save(string)Savesthegametothefilewithnamestring.game_load(string)Loadsthegamefromthefilewithnamestring.

Pleaserealizethatonlythebasicgamedataisbeingsaved.Ifforexampleyouplayaparticularpieceofmusic,theprecisepositioninthemusicisnotsaved.Alsochangedresourcesarenotsaved.Otherthingsthatarenotsavedarethecontentsofdatastructures,particles,andmultiplayersettings.

Page 259: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Transitions

Whenyoumovefromoneroomtoanotheryoucanselectatransition.Tosetthetransitiontothenextframeyoumustsetthevariablecalledtransition_kind.Ifyouassignavaluelargerthan0toitthecorrespondingtransitionisusedforthenextroomtransition.Itonlyaffectthenexttransition.Afterthisthevalueisresetto0,whichindicatesnotransition.

transition_kindIndicatesthenextroomtransition.Youcanusethefollowingbuiltinvalues

0=noeffect1=Createfromleft2=Createfromright3=Createfromtop4=Createfrombottom5=Createfromcenter6=Shiftfromleft7=Shiftfromright8=Shiftfromtop9=Shiftfrombottom10=Interlacedfromleft11=Interlacedfromright12=Interlacedfromtop13=Interlacedfrombottom14=Pushfromleft15=Pushfromright16=Pushfromtop17=Pushfrombottom18=Rotatetotheleft19=Rotatetotheright20=Blendtherooms21=Fadeoutandin

transition_stepsIndicatesthenumberofstepsinthetransition.The

Page 260: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

moresteps,thelongerthetransitiontakes.Defaultis80.transition_define(kind,name)Youcanactuallycreateyourowntransitions.Tothisendyoumustdefineascript(possiblyinanextensionpackage)todothetransition.Withthisfunctionyoucanthenaddthetransitiontothesystem.kindistheindexofthetransition(eitheranewoneoranexistingtransitions).nameisthenameofthescript.Notethatthenameofthescriptisastring!Sotheremustbequotesaroundit.Notethatthisisreallyadvancedstuff.Thescriptmusttakefivearguments:asurfacewiththeimageofthepreviousroom,asurfacewiththeimageofthenextroom,thewidthofthesurfaces,theheightofthesurfaces,andthefractionofthetransition(between0and1).Itmustthendrawtheimageusingthetwosurfaces.transition_exists(kind)Thisfunctionreturnswhetheratransitionoftheindicatedkindexists.

Pleasenotethattransitionsdonotworkwhenusingusing3dgraphics.Also,roomtransitionsingeneraldonotworkcorrectlywhenthesizesoftherooms(ortobemorepreciseoftheregiononthescreen)arenotthesame.

Page 261: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Score

Otherimportantaspectsofmanygamesarethescore,thehealth,andthenumberoflives.GameMakerkeepstrackofthescoreinaglobalvariablescoreandthenumberoflivesinaglobalvariablelives.Youcanchangethescorebysimplychangingthevalueofthisvariable.Thesameappliestohealthandlives.Iflivesislargerthan0andbecomessmallerthanorequalto0theno-more-liveseventisperformedforallinstances.Ifyoudon'twanttoshowthescoreandlivesinthecaption,setthevariableshow_score,etc.,tofalse.Alsoyoucanchangethecaption.Formorecomplicatedgamesbestdisplaythescoreyourself.

scoreThecurrentscore.livesNumberoflives.healthThecurrenthealth(0-100).show_scoreWhethertoshowthescoreinthewindowcaption.show_livesWhethertoshowthenumberoflivesinthewindowcaption.show_healthWhethertoshowthehealthinthewindowcaption.caption_scoreThecaptionusedforthescore.caption_livesThecaptionusedforthenumberoflives.caption_healthThecaptionusedforthehealth.

Page 262: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Generatingevents

Asyouknow,GameMakeriscompletelyeventdriven.Allactionshappenastheresultofevents.Thereareanumberofdifferentevents.Creationanddestroyeventshappenwhenaninstanceiscreatedordestroyed.Ineachstep,thesystemfirsthandlesthebeginstepevents.Nextithandlesthealarmevents,keyboardandmouseeventsandnextthestepevent.Afterthistheinstancesaresettotheirnewpositionsafterwhichthecollisioneventishandled.Finallytheendstepeventsarehandledafterwhichthedraweventisusedtodrawtheinstances(notethatwhentherearemultipleviewsthedraweventiscalledmultipletimesineachstep).Youcanalsoapplyaneventtothecurrentinstancefromwithinapieceofcode.Thefollowingfunctionsexist:

event_perform(type,numb)Performseventnumboftheindicatedtypetothecurrentinstance.Thefollowingeventtypescanbeindicated:

ev_createev_destroyev_step

ev_alarm

ev_keyboard

ev_mouse

ev_collision

ev_other

ev_draw

ev_keypress

ev_keyrelease

ev_trigger

Whentherearemultipleeventsofthegiventype,numbcanbeusedtospecifythepreciseevent.Fortheeventtypeev_alarmnumbcanrangefrom0to11.Fortheev_keyboard,ev_keypress.andev_keyreleaseeventtypesyouhavetousethekeycodeforthekey.Forev_mouseeventsyoucanusefornumbthefollowingconstants:

ev_left_button

ev_right_button

Page 263: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ev_middle_button

ev_no_button

ev_left_press

ev_right_press

ev_middle_press

ev_left_release

ev_right_release

ev_middle_release

ev_mouse_enter

ev_mouse_leave

ev_mouse_wheel_up

ev_mouse_wheel_down

ev_global_left_button

ev_global_right_button

ev_global_middle_button

ev_global_left_press

ev_global_right_press

ev_global_middle_press

ev_global_left_release

ev_global_right_release

ev_global_middle_release

ev_joystick1_left

ev_joystick1_right

ev_joystick1_up

ev_joystick1_down

ev_joystick1_button1

ev_joystick1_button2

ev_joystick1_button3

ev_joystick1_button4

ev_joystick1_button5

ev_joystick1_button6

ev_joystick1_button7

ev_joystick1_button8

ev_joystick2_left

ev_joystick2_right

ev_joystick2_up

ev_joystick2_down

ev_joystick2_button1

ev_joystick2_button2

ev_joystick2_button3

ev_joystick2_button4

ev_joystick2_button5

ev_joystick2_button6

ev_joystick2_button7

ev_joystick2_button8

Forthecollisioneventyougivetheindexoftheotherobject.Forthe

Page 264: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

eventtypeev_otheryoucanusefornumbthefollowingconstants:

ev_outside

ev_boundary

ev_game_start

ev_game_end

ev_room_start

ev_room_end

ev_no_more_lives

ev_no_more_health

ev_animation_end

ev_end_of_path

ev_close_button

ev_user0

ev_user1

ev_user2

ev_user3

ev_user4

ev_user5

ev_user6

ev_user7

ev_user8

ev_user9

ev_user10

ev_user11

ev_user12

ev_user13

ev_user14

ev_user15

Fortheev_stepeventtypeyoucanusethefollowingconstantsfornumb:

ev_step_normal

ev_step_begin

ev_step_end

Finallyfortheev_triggereventtypeyoushouldusetheconstantsthatyoucanspecifywhendefiningtheseevents.event_perform_object(obj,type,numb)Thisfunctionsworksthesameasthefunctionaboveexceptthatthistimeyoucanspecifyeventsinanotherobject.Notethattheactionsintheseeventsareappliedtothecurrentinstance,nottoinstancesofthegivenobject!event_user(numb)Intheothereventsyoucanalsodefine16user

Page 265: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

events.Theseareonlyperformedifyoucallthisfunction.numbmustlieintherange0to15.event_inherited()Performstheinheritedevent.Thisonlyworksiftheinstancehasaparentobject.

Youcangetinformationaboutthecurrenteventbeingexecutedusingthefollowingread-onlyvariables:

event_type*Typeofthecurrenteventbeginexecuted.event_number*Numberofthecurrenteventbeginexecuted.event_object*Theobjectindexforwhichthecurrenteventisbeingexecuted.event_action*Theindexoftheactionthatiscurrentlybeingexecuted(0isthefirstintheevent,etc.).

Page 266: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Miscellaneousvariablesandfunctions

Herearesomevariablesandfunctionsthatdealwitherrors.

error_occurredIndicateswhetheranerrorhasoccurred.error_lastStringindicatingthelasterrormessage.show_debug_message(str)Showsthestringindebugmode.debug_modeThisread-onlyvariableindicateswhetherthegameisrunningindebugmode.

ThefollowingvariablescanbeusedtomakesureyourcodewillworkfortheappropriateversionandeditionofGameMaker.

gamemaker_proIndicateswhetherthegameiscreatedwiththeProEdition.gamemaker_registeredSameasgamemaker_progamemaker_versionTheversionofGameMaker.Thisisaninteger.Forversion8.0thiscanbeanythingbetween800and809.Forversion8.1thiswillbesomethingbetween810and819,etc.Sonevercheckaparticularversionbutbettercheckforarange.Thisvariableisnotavailableinversionbefore800.

Thefollowingfunctionsexistthatallowyoutocheckwhethercertainvariablesexistandwithwhichyoucansetvariablesandgettheirvalues.Inallthesefunctionsthevariablenameispassedasastring!

variable_global_exists(name)Returnswhetheraglobalvariablewiththegivenname(astring)exists.variable_local_exists(name)Returnswhetheralocalvariablewiththegivenname(astring)existsforthecurrentinstance.variable_global_get(name)Returnsthevalueoftheglobalvariablewiththegivenname(astring).variable_global_array_get(name,ind)Returnsthevalueofindexindoftheglobalarrayvariablewiththegivenname(astring).variable_global_array2_get(name,ind1,ind2)Returnsthevalueofindexind1,ind2oftheglobal2-dimensionalarrayvariablewiththe

Page 267: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

givenname(astring).variable_local_get(name)Returnsthevalueofthelocalvariablewiththegivenname(astring).variable_local_array_get(name,ind)Returnsthevalueofindexindofthelocalarrayvariablewiththegivenname(astring).variable_local_array2_get(name,ind1,ind2)Returnsthevalueofindexind1,ind2ofthelocal2-dimensionalarrayvariablewiththegivenname(astring).variable_global_set(name,value)Setstheglobalvariablewiththegivenname(astring)tothegivenvalue.variable_global_array_set(name,ind,value)Setstheindexindintheglobalarrayvariablewiththegivenname(astring)tothegivenvalue.variable_global_array2_set(name,ind1,ind2,value)Setstheindexind1,ind2intheglobal2-dimensionalarrayvariablewiththegivenname(astring)tothegivenvalue.variable_local_set(name,value)Setsthelocalvariablewiththegivenname(astring)tothegivenvalue.variable_local_array_set(name,ind,value)Setstheindexindinthelocalarrayvariablewiththegivenname(astring)tothegivenvalue.variable_local_array2_set(name,ind1,ind2,value)Setstheindexind1,ind2inthelocal2-dimensionalarrayvariablewiththegivenname(astring)tothegivenvalue.

Forexample,youcanwrite:

{

ifvariable_global_exists('ammunition')

global.ammunition+=1

else

global.ammunition=0

}

Youcanalsousethesefunctionstopassvariablestoascriptinasortofby-referenceway,bypassingtheirnamesasstringsandusingthefunctionstochangethem.

Youcanchangetheprogrampriorityusingthefollowingfunction:

Page 268: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

set_program_priority(priority)Setsthepriorityfortheprogram.Youcanindicateavaluebetween-3and+3.Avalueof-3meansthattheprogramwillonlyrunifnootherprocessonthecomputerrequiresprocessingtime,orstateddifferently,whenallotherprocessesareidle.Valuesof-2and-1arebelownormal,sootherprocesseswillgetpriority.0isthenormalvalue.+1and+2giveahigherpriority,resultingpossiblyinhigherspeedandsmoothergameflow.Butotherprocesseswillgetmuchlessprocessingtime.+3indicatesreal-timemode.Inreal-timemodebasicallyalltimeisallottedtothegame.Thiscanleadtoseriousproblemswithanyotherapplicationsrunningonthecomputer.Alsokeyboardeventsande.g.thepressingofthecloseboxmightnolongerberecordedbyWindows.Soonlyusethisifyouwantalltheprocessortime.Alsobettercheckcarefullybeforeusingitandsavethegamebeforerunning.

Finally,youcanusethefollowingfunctiontosetthetitleoftheapplication:

set_application_title(title)Setsthetitleoftheapplicationtothegivenstring.Thetitleisforexampleshowninthetaskbar.

Page 269: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Userinteraction

Thereisnogamewithoutinteractionwiththeuser.ThestandardwayofdoingthisinGameMakeristoputactionsinmouseorkeyboardevents.Butsometimesyouneedmorecontrol.Fromwithinapieceofcodeyoucancheckwhethercertainkeysonthekeyboardarepressedandyoucancheckforthepositionofthemouseandwhetheritsbuttonsarepressed.Normallyyouchecktheseaspectsinthestepeventofsomecontrollerobjectandtakeactionaccordingly.

Informationonuserinteractioncanbefoundinthefollowingpages:

TheKeyboardTheMouseTheJoystick

Page 270: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thekeyboard

Forkeyboardinteraction,thefollowingvariablesandfunctionsexist:

keyboard_lastkeyKeycodeoflastkeypressed.Seebelowforkeycodeconstants.Youcanchangeit,e.g.setitto0ifyouhandledit.keyboard_keyKeycodeofcurrentkeypressed(seebelow;0ifnone).keyboard_lastcharLastcharacterpressed(asstring).keyboard_stringStringcontainingthelastatmost1024characterstyped.Thisstringwillonlycontaintheprintablecharacterstyped.Italsocorrectlyrespondstopressingthebackspacekeybyerasingthelastcharacter.

Sometimesitisusefultomaponekeytoanother.Forexampleyoumightwanttoallowtheplayertouseboththearrowkeysandthenumpadkeys.Ratherthanduplicatingtheactionsyoucanmapthenumpadkeystothearrowkeys.Alsoyoumightwanttoimplementamechanisminwhichtheplayercansetthekeystouse.Forthisthefollowingfunctionsareavailable:

keyboard_set_map(key1,key2)Mapsthekeywithkeycodekey1tokey2.keyboard_get_map(key)Returnsthecurrentmappingforkey.keyboard_unset_map()Resetsallkeystomaptothemselves.

Tocheckwhetheraparticularkeyormousebuttonispressedyoucanusethefollowingfunctions.Thisisinparticularusefulwhenmultiplekeysarepressedsimultaneously.

keyboard_check(key)Returnswhetherthekeywiththeparticularkeycodeiscurrentlydown.keyboard_check_pressed(key)Returnswhetherthekeywiththeparticularkeycodewaspressedsincethelaststep.keyboard_check_released(key)Returnswhetherthekeywiththeparticularkeycodewasreleasedsincethelaststep.

Page 271: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

keyboard_check_direct(key)Returnswhetherthekeywiththeparticularkeycodeispressedbycheckingthehardwaredirectly.Theresultisindependentofwhichapplicationhasfocus.Itallowsforafewmorechecks.Inparticularyoucanusekeycodesvk_lshift,vk_lcontrol,vk_lalt,vk_rshift,vk_rcontrolandvk_ralttocheckwhethertheleftorrightshift,controloraltkeyispressed.

Thefollowingroutinescanbeusedtomanipulatethekeyboardstate:

keyboard_get_numlock()Returnswhetherthenumlockisset.keyboard_set_numlock(on)Sets(true)orunsets(false)thenumlock.keyboard_key_press(key)Simulatesapressofthekeywiththeindicatedkeycode.keyboard_key_release(key)Simulatesareleaseofthekeywiththeindicatedkeycode.

Thefollowingconstantsforvirtualkeycodesexist:

vk_nokeykeycoderepresentingthatnokeyispressedvk_anykeykeycoderepresentingthatanykeyispressedvk_leftkeycodeforleftarrowkeyvk_rightkeycodeforrightarrowkeyvk_upkeycodeforuparrowkeyvk_downkeycodefordownarrowkeyvk_enterenterkeyvk_escapeescapekeyvk_spacespacekeyvk_shiftshiftkeyvk_controlcontrolkeyvk_altaltkeyvk_backspacebackspacekeyvk_tabtabkeyvk_homehomekeyvk_endendkeyvk_deletedeletekeyvk_insertinsertkeyvk_pageuppageupkeyvk_pagedownpagedownkey

Page 272: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

vk_pausepause/breakkeyvk_printscreenprintscreen/sysrqkeyvk_f1...vk_f12keycodesforthefunctionkeysF1toF12vk_numpad0...vk_numpad9numberkeysonthenumerickeypadvk_multiplymultiplykeyonthenumerickeypadvk_dividedividekeyonthenumerickeypadvk_addaddkeyonthenumerickeypadvk_subtractsubtractkeyonthenumerickeypadvk_decimaldecimaldotkeysonthenumerickeypad

Fortheletterkeysuseforexampleord('A').(Thecapitalletters.)Forthedigitkeysuseforexampleord('5')togetthe<5>key.Thefollowingconstantscanonlybeusedinkeyboard_check_direct:

vk_lshiftleftshiftkeyvk_lcontrolleftcontrolkeyvk_laltleftaltkeyvk_rshiftrightshiftkeyvk_rcontrolrightcontrolkeyvk_raltrightaltkey

Forexample,assumeyouhaveanobjectthattheusercancontrolwiththearrowkeysyoucanputthefollowingpieceofcodeinthestepeventoftheobject:

{

if(keyboard_check(vk_left))x-=4;

if(keyboard_check(vk_right))x+=4;

if(keyboard_check(vk_up))y-=4;

if(keyboard_check(vk_down))y+=4;

}

Ofcourseitisaloteasiertosimplyputthisinthekeyboardevents.

Therearesomeadditionalfunctionsrelatedtokeyboardinteraction.

keyboard_clear(key)Clearsthestateofthekey.Thismeansthatitwillnolongergeneratekeyboardeventsuntilitstartsrepeating.io_clear()Clearsallkeyboardandmousestates.

Page 273: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

io_handle()Handleuserio,updatingkeyboardandmousestatus.keyboard_wait()Waitstilltheuserpressesakeyonthekeyboard.

Page 274: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Themouse

Formouseinteraction,thefollowingvariablesandfunctionsexist:

mouse_x*X-coordinateofthemouseintheroom.Cannotbechanged.mouse_y*Y-coordinateofthemouseintheroom.Cannotbechanged.mouse_buttonCurrentlypressedmousebutton.Asvalueusemb_none,mb_any,mb_left,mb_middle,ormb_right.mouse_lastbuttonLastpressedmousebutton.

Tocheckwhetheraparticularmousebuttonispressedyoucanusethefollowingfunctions.Thisisinparticularusefulwhenmultiplekeysarepressedsimultaneously.

mouse_check_button(numb)Returnswhetherthemousebuttoniscurrentlydown(useasvaluesmb_none,mb_left,mb_middle,ormb_right).mouse_check_button_pressed(numb)Returnswhetherthemousebuttonwaspressedsincethelaststep.mouse_check_button_released(numb)Returnswhetherthemousebuttonwasreleasedsincethelaststep.

Thefollowingfunctionscanbeusedtocheckwhetherthemousewheelwasused.

mouse_wheel_up()Returnswhetherthemousewheelwasmovedupsincethelaststep.mouse_wheel_down()Returnswhetherthemousewheelwasmoveddownsincethelaststep.

Therearesomeadditionalfunctionsrelatedtomouseinteraction.

mouse_clear(button)Clearsthestateofthemousebutton.Thismeansthatitwillnolongergeneratemouseeventsuntiltheplayer

Page 275: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

releasesitandpressesitagain.io_clear()Clearsallkeyboardandmousestates.io_handle()Handleuserio,updatingkeyboardandmousestatus.mouse_wait()Waitstilltheuserpressesamousebutton.

Youcanchangethewaythemousecursorlookslike.Youcanchooseanyspriteforthis.Tothisendyoucanusethefollowingvariable:

cursor_spriteIndicatesthespritethatisusedtorepresentthecursor(defaultnospriteisused,representedbyavalueof-1).Youcanassignoneofthespritestothisvariabletohaveitbeendrawnautomaticallyatthepositionofthemousecursor.(YoucanalsoswitchoffthewindowsmousecursorintheGlobalGameSettings.)

Page 276: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thejoystick

Therearesomeeventsassociatedwithjoysticks.Buttohavefullcontroloverthejoysticksthereisawholesetoffunctionstodealwithjoysticks.GameMakersupportsuptotwojoysticks.Soallofthesefunctionstakeajoystickidasargument.

joystick_exists(id)Returnswhetherjoystickid(1or2)exists.joystick_name(id)Returnsthenameofthejoystickjoystick_axes(id)Returnsthenumberofaxesofthejoystick.joystick_buttons(id)Returnsthenumberofbuttonsofthejoystick.joystick_has_pov(id)Returnswhetherthejoystickhaspoint-of-viewcapabilities.joystick_direction(id)Returnsthekeycode(vk_numpad1tovk_numpad9)correspondingtothedirectionofjoystickid(1or2).joystick_check_button(id,numb)Returnswhetherthejoystickbuttonispressed(numbintherange1-32).joystick_xpos(id)Returnstheposition(-1to1)ofthex-axisofjoystickid.joystick_ypos(id)Returnsthejoysticksy-position.joystick_zpos(id)Returnsthejoysticksz-position(ifithasaz-axis).joystick_rpos(id)Returnsthejoysticksrudderposition(orfourthaxis).joystick_upos(id)Returnsthejoysticksu-position(orfifthaxis).joystick_vpos(id)Returnsthejoysticksv-position(orsixthaxis).joystick_pov(id)Returnsthejoystickspoint-ofviewposition.Thisisananglebetween0and360degrees.0isforwards,90totheright,180backwardsand270totheleft.Whennopoint-of-viewdirectionispressedbytheuser-1isreturned.

Page 277: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Gamegraphics

Animportantpartofagameisthegraphics.GameMakernormallytakescareofmostofthisandforsimplegamesthereisneedtoworryaboutit.Butsometimesyouwanttotakemorecontrol.Forsomeaspectsthereareactionsbutfromcodeyoucancontrolmanymoreaspects.Thischapterdescribesallvariablesandfunctionsavailableforthisandgivessomemoreinformationaboutwhatisreallyhappening.

Informationongamegraphicscanbefoundinthefollowingpages:

SpritesandImagesBackgroundsDrawingSpritesandBackgroundsDrawingShapesFontsandTextAdvancedDrawingFunctionsDrawingSurfacesTilesTheDisplayTheWindowViewsRepaintingtheScreen

Page 278: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Spritesandimages

Eachobjecthasaspriteassociatedwithit.Thisiseitherasingleimageoritconsistsofmultipleimages.Foreachinstanceoftheobjecttheprogramdrawsthecorrespondingimageonthescreen,withitsorigin(asdefinedinthespriteproperties)attheposition(x,y)oftheinstance.Whentherearemultipleimages,itcyclesthroughtheimagestogetananimationeffect.Thereareanumberofvariablesthataffectthewaytheimageisdrawn.Thesecanbeusedtochangetheeffects.Eachinstancehasthefollowingvariables:

visibleIfvisibleistrue(1)theimageisdrawn,otherwiseitisnotdrawn.Invisibleinstancesarestillactiveandcreatecollisionevents;onlyyoudon'tseethem.Settingthevisibilitytofalseisusefulfore.g.controllerobjects(makethemnon-solidtoavoidcollisionevents)orhiddenswitches.sprite_indexThisistheindexofthecurrentspritefortheinstance.Youcanchangeittogivetheinstanceadifferentsprite.Asvalueyoucanusethenamesofthedifferentspritesyoudefined.Changingthespritedoesnotchangetheindexofthecurrentlyvisiblesubimage.sprite_width*Indicatesthewidthofthesprite.Thisvaluecannotbechangedbutyoumightwanttouseit.sprite_height*Indicatestheheightofthesprite.Thisvaluecannotbechangedbutyoumightwanttouseit.sprite_xoffset*Indicatesthehorizontaloffsetofthespriteasdefinedinthespriteproperties.Thisvaluecannotbechangedbutyoumightwanttouseit.sprite_yoffset*Indicatestheverticaloffsetofthespriteasdefinedinthespriteproperties.Thisvaluecannotbechangedbutyoumightwanttouseit.image_number*Thenumberofsubimagesforthecurrentspritefortheinstance(cannotbechanged).image_indexWhentheimagehasmultiplesubimagestheprogramcyclesthroughthem.Thisvariableindicatesthecurrentlydrawnsubimage(theyarenumberedstartingfrom0).Youcanchangethe

Page 279: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

currentimagebychangingthisvariable.Theprogramwillcontinuecycling,startingatthisnewindex.(Thevaluecanhaveafractionalpart.Inthiscaseitisalwaysroundeddowntoobtainthesubimagethatisdrawn.)image_speedThespeedwithwhichwecyclethroughthesubimages.Avalueof1indicatesthateachstepwegetthenextimage.Smallervalueswillswitchsubimagesslower,drawingeachsubimagemultipletimes.Largervalueswillskipsubimagestomakethemotionfaster.Sometimesyouwantaparticularsubimagetobevisibleanddon'twanttheprogramtocyclethroughallofthem.Thiscanbeachievedbysettingthespeedto0andchoosingthecorrectsubimage.Forexample,assumeyouhaveanobjectthatcanrotateandyoucreateaspritethathassubimagesforanumberoforientations(counter-clockwise).Then,inthestepeventoftheobjectyoucanset

{

image_index=direction*image_number/360;

image_speed=0;

}

depthNormallyimagesaredrawnintheorderinwhichtheinstancesarecreated.Youcanchangethisbysettingtheimagedepth.Thedefaultvalueis0,unlessyousetittoadifferentvalueintheobjectproperties.Thehigherthevaluethefurthertheinstanceisaway.(Youcanalsousenegativevalues.)Instanceswithhigherdepthwillliebehindinstanceswithalowerdepth.Settingthedepthwillguaranteethattheinstancesaredrawnintheorderyouwant(e.g.theplaneinfrontofthecloud).Backgroundinstancesshouldhaveahigh(positive)depth,andforegroundinstancesshouldhavealow(negative)depth.image_xscaleAscalefactortomakelargerorsmallerimages.Avalueof1indicatesthenormalsize.Youmustseparatelysetthehorizontalxscaleandverticalyscale.Changingthescalealsochangesthevaluesfortheimagewidthandheightandinfluencescollisioneventsasyoumightexpect.Changingthescalecanbeusedtogeta3-Deffect.Youcanuseavalueof-1tomirrorthespritehorizontally.

Page 280: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

image_yscaleTheverticalyscale.1isnoscaling.Youcanuseavalueof-1toflipthespritevertically.image_angleTheanglewithwhichthespriteisrotated.Youspecifythisindegrees,counterclockwise.Avalueof0indicatesnorotation.ThisvariablecanonlybesetintheProEdition!image_alphaTransparency(alpha)valuetousewhendrawingtheimage.Avalueof1isthenormalopaquesetting;avalueof0iscompletelytransparent.image_blendBlendingcolorusedwhendrawingthesprite.Avalueofc_whiteisthedefault.Whenyouspecifyadifferentvaluetheimageisblendedwiththiscolor.Thiscanbeusedtocolorizethespriteonthefly.ThisvariablecanonlybesetintheProEdition!bbox_left*Leftsideoftheboundingboxoftheinstanceintheroom,asdefinedbyitsimage(takingscalingintoaccount).bbox_right*Rightsideoftheboundingboxoftheinstanceintheroom.bbox_top*Topsideoftheboundingboxoftheinstanceintheroom.bbox_bottom*Bottomsideoftheboundingboxoftheinstanceintheroom.

Page 281: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Backgrounds

Eachroomcanhaveupto8backgrounds.Alsoithasabackgroundcolor.Allaspectsofthesebackgroundsyoucanchangeinapieceofcodeusingthefollowingvariables(notethatsomearearraysthatrangefrom0to7,indicatingthedifferentbackgrounds):

background_colorBackgroundcolorfortheroom.background_showcolorWhethertoclearthewindowinthebackgroundcolor.background_visible[0..7]Whethertheparticularbackgroundimageisvisible.background_foreground[0..7]Whetherthebackgroundisactuallyaforeground.background_index[0..7]Backgroundimageindexforthebackground.background_x[0..7]Xpositionofthebackgroundimage.background_y[0...7]Ypositionofthebackgroundimage.background_width[0...7]*Widthofthebackgroundimage.background_height[0...7]*Heightofthebackgroundimage.background_htiled[0..7]Whetherhorizontallytiled.background_vtiled[0..7]Whetherverticallytiled.background_xscale[0..7]Horizontalscalingfactorforthebackground.(Thismustbepositive;youcannotuseanegativevaluetomirrorthebackground.)background_yscale[0..7]Verticalscalingfactorforthebackground.(Thismustbepositive;youcannotuseanegativevaluetoflipthebackground.)background_hspeed[0..7]Horizontalscrollingspeedofthebackground(pixelsperstep).background_vspeed[0..7]Verticalscrollingspeedofthebackground(pixelsperstep).background_blend[0..7]Blendingcolortousewhendrawingthebackground.Avalueofc_whiteisthedefault.OnlyavailableintheProEdition!

Page 282: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

background_alpha[0..7]Transparency(alpha)valuetousewhendrawingthebackground.Avalueof1isthenormalsetting;avalueof0iscompletelytransparent.

Page 283: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Drawingspritesandbackgrounds

Objectsnormallyhaveaspriteassociatedtoitthatisdrawn.Butyoucanusethedraweventtodrawotherthings.Thissectionandthenextcouplegiveyouinformationonwhatispossible.Firstofall,therearefunctionstodrawspritesandbackgroundsindifferentways.Thesegiveyoumorecontrolovertheappearanceofthesprite.Alsoyoucandraw(partsof)backgrounds.

draw_sprite(sprite,subimg,x,y)Drawssubimagesubimg(-1=current)ofthespritewithitsoriginatposition(x,y).(Withoutcolorblendingandnoalphatransparency.)draw_sprite_stretched(sprite,subimg,x,y,w,h)Drawsthespritestretchedsothatitfillstheregionwithtop-leftcorner(x,y)andwidthwandheighth.draw_sprite_tiled(sprite,subimg,x,y)Drawsthespritetiledsothatitfillstheentireroom.(x,y)istheplacewhereoneofthespritesisdrawn.draw_sprite_part(sprite,subimg,left,top,width,height,x,y)Drawstheindicatedpartofsubimagesubimg(-1=current)ofthespritewiththetop-leftcornerofthepartatposition(x,y).

draw_background(back,x,y)Drawsthebackgroundatposition(x,y).(Withoutcolorblendingandnoalphatransparency.)draw_background_stretched(back,x,y,w,h)Drawsthebackgroundstretchedtotheindicatedregion.draw_background_tiled(back,x,y)Drawsthebackgroundtiledsothatitfillstheentireroom.draw_background_part(back,left,top,width,height,x,y)Drawstheindicatedpartofthebackgroundwiththetop-leftcornerofthepartatposition(x,y).

Thefollowingfunctionsareextendedfunctionsoftheonesindicatedabove.TheseextendedversionscanonlybeusedintheProEdition!

draw_sprite_ext(sprite,subimg,x,y,xscale,yscale,rot,color,alpha)

Page 284: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Drawsthespritescaledwithfactorsxscaleandyscaleandrotatedcounterclockwiseoverrotdegrees.coloristheblendingcolor(usec_whitefornoblending)andalphaindicatesthetransparencyfactorwithwhichtheimagesismergedwithitsbackground.Avalueof0makesthespritecompletelytransparent.Avalueof1makesitcompletelysolid.Thisfunctioncancreategreateffect(forexamplepartiallytransparentexplosions).draw_sprite_stretched_ext(sprite,subimg,x,y,w,h,color,alpha)

Drawsthespritestretchedsothatitfillstheregionwithtop-leftcorner(x,y)andwidthwandheighth.coloristheblendingcolorandalphaindicatesthetransparencysetting.draw_sprite_tiled_ext(sprite,subimg,x,y,xscale,yscale,color,alpha)

Drawsthespritetiledsothatitfillstheentireroombutnowwithscalefactorsandacolorandtransparencysetting.draw_sprite_part_ext(sprite,subimg,left,top,width,height,x,y,xscale,yscale,color,alpha)

Drawstheindicatedpartofsubimagesubimg(-1=current)ofthespritewiththetop-leftcornerofthepartatposition(x,y)butnowwithscalefactorsandacolorandtransparencysetting.draw_sprite_general(sprite,subimg,left,top,width,height,x,y,xscale,yscale,rot,c1,c2,c3,c4,alpha)

Themostgeneraldrawingfunction.Itdrawstheindicatedpartofsubimagesubimg(-1=current)ofthespritewiththetop-leftcornerofthepartatposition(x,y)butnowwithscalefactors,arotationangle,acolorforeachofthefourvertices(top-left,top-right,bottom-right,andbottom-left),andanalphatransparencyvalue.Notethatrotationtakesplacearoundthetop-leftcornerofthepart.

draw_background_ext(back,x,y,xscale,yscale,rot,color,alpha)

Drawsthebackgroundscaledandrotatedwithblendingcolor(usec_whitefornoblending)andtransparencyalpha(0-1).draw_background_stretched_ext(back,x,y,w,h,color,alpha)Drawsthebackgroundstretchedtotheindicatedregion.coloristheblendingcolorandalphaindicatesthetransparencysetting.draw_background_tiled_ext(back,x,y,xscale,yscale,color,alpha)

Drawsthebackgroundtiledsothatitfillstheentireroombutnowwithscalefactorsandacolorandtransparencysetting.draw_background_part_ext(back,left,top,width,height,x,y,xscale,yscale,color,alpha)

Drawstheindicatedpartofthebackgroundwiththetop-leftcornerofthepartatposition(x,y)butnowwithscalefactorsandacolorand

Page 285: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

transparencysetting.draw_background_general(back,left,top,width,height,x,y,xscale,yscale,rot,c1,c2,c3,c4,alpha)

Themostgeneraldrawingfunction.Itdrawstheindicatedpartofthebackgroundwiththetop-leftcornerofthepartatposition(x,y)butnowwithscalefactors,arotationangle,acolorforeachofthefourvertices(top-left,top-right,bottom-right,andbottom-left),andanalphatransparencyvalue.Notethatrotationtakesplacearoundthetop-leftcornerofthepart.

Page 286: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Drawingshapes

Thereisawholecollectionoffunctionsavailabletodrawdifferentshapes.Alsotherearefunctionstodrawtext(seenextsection).Youcanonlyusetheseinthedrawingeventofanobject;thesefunctionsingeneraldon'tmakeanysenseanywhereelseincode.Realizethatcollisionsbetweeninstancesaredeterminedbytheirsprites(ormasks)andnotbywhatyouactuallydraw.Thefollowingdrawingfunctionsexistthatcanbeusedtodrawbasicshapes.

draw_clear(col)Clearstheentireroominthegivencolor(noalphablending).draw_clear_alpha(col,alpha)Clearstheentireroominthegivencolorandalphavalue(inparticularusefulforsurfaces).draw_point(x,y)Drawsapointat(x,y)inthecurrentcolor.draw_line(x1,y1,x2,y2)Drawsalinefrom(x1,y1)to(x2,y2).draw_line_width(x1,y1,x2,y2,w)Drawsalinefrom(x1,y1)to(x2,y2)withwidthw.draw_rectangle(x1,y1,x2,y2,outline)Drawsarectangle.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).draw_roundrect(x1,y1,x2,y2,outline)Drawsaroundedrectangle.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).draw_triangle(x1,y1,x2,y2,x3,y3,outline)Drawsatriangle.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).draw_circle(x,y,r,outline)Drawsacircleat(x,y)withradiusr.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).draw_ellipse(x1,y1,x2,y2,outline)Drawsanellipse.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).draw_set_circle_precision(precision)Setstheprecisionwithwhichcirclesaredrawn,thatis,thenumberofsegmentstheyconsistof.

Page 287: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Theprecisionmustliebetween4and64andmustbedividableby4.Thisisalsousedfordrawingellipsesandroundedrectangles.draw_arrow(x1,y1,x2,y2,size)Drawsanarrowfrom(x1,y1)to(x2,y2).sizeindicatesthesizeofthearrowinpixels.draw_button(x1,y1,x2,y2,up)Drawsabutton,upindicateswhetherup(1)ordown(0).draw_path(path,x,y,absolute)Withthisfunctionyoucandrawtheindicatedpathintheroomwithitsstartatposition(x,y).Ifabsoluteistruethepathisdrawnatthepositionwhereitwasdefinedandthevaluesofxandyareignored.draw_healthbar(x1,y1,x2,y2,amount,backcol,mincol,maxcol,direction,showback,showborder)

Withthisfunctionyoucandrawahealthbar(oranyotherbarthatindicatessomevalue,likee.g.thedamage).Theargumentsx1,y1,x2andy2indicatethetotalareaforthebar.amountindicatesthepercentageofthebarthatmustbefilled(mustliebetween0and100).backcolisthecolorofthebackgroundforthebar.mincolandmaxcolindicatethecolorwhentheamountis0and100respectively.Foranamountinbetweenthecolorisinterpolated.Soyoucaneasilymakeabarthatgoese.g.fromgreentored.Thedirectionisthedirectioninwhichthebarisdrawn.0indicatesthatthebarisanchoredattheleft,1attheright,2atthetopand3atthebottom.Finallyshowbackindicateswhetherabackgroundboxmustbeshownandshowborderindicatedwhethertheboxandbarshouldhaveablackborderline.

Mostoftheabovefunctionsusethecolorandalphasettingthatcanbechangedwithfollowingfunctions.

draw_set_color(col)Setsthedrawingcolortobeusedfromnowonfordrawingprimitives.draw_set_alpha(alpha)Setsthealphatransparencyvaluetobeusedfromnowonfordrawingprimitives.Shouldlieintherange0-1.0isfullytransparent,1isfullyopaque.draw_get_color()Returnsthedrawingcolorusedfordrawingprimitives.draw_get_alpha()Returnsthealphavalueusedfordrawingprimitives.

Page 288: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Awholerangeofpredefinedcolorsisavailable:

c_aqua

c_black

c_blue

c_dkgray

c_fuchsia

c_gray

c_green

c_lime

c_ltgray

c_maroon

c_navy

c_olive

c_orange

c_purple

c_red

c_silver

c_teal

c_white

c_yellow

Thefollowingfunctionscanhelpyoutocreatethecolorsyouwant.

make_color_rgb(red,green,blue)Returnsacolorwiththeindicatedred,green,andbluecomponents,wherered,greenandbluemustbevaluesbetween0and255.make_color_hsv(hue,saturation,value)Returnsacolorwiththeindicatedhue,saturationandvaluecomponents(eachbetween0and255).color_get_red(col)Returnstheredcomponentofthecolor.color_get_green(col)Returnsthegreencomponentofthecolor.color_get_blue(col)Returnsthebluecomponentofthecolor.color_get_hue(col)Returnsthehuecomponentofthecolor.color_get_saturation(col)Returnsthesaturationcomponentofthecolor.color_get_value(col)Returnsthevaluecomponentofthecolor.merge_color(col1,col2,amount)Returnsamergedcolorofcol1andcol2.Themergingisdeterminedbyamount.Avalueof0correspondstocol1,avalueof1tocol2,andvaluesinbetweentomergedvalues.

Page 289: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thefollowingmiscellaneousfunctionsexist.

draw_getpixel(x,y)Returnsthecolorofthepixelcorrespondingtoposition(x,y)intheroom.Thisisnotveryfast,sousewithcare.screen_save(fname)Savesapngimageofthescreeninthegivenfilename.Usefulformakingscreenshots.screen_save_part(fname,x,y,w,h)Savespartofthescreeninthegivenpngfilename.

Page 290: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Fontsandtext

Ingamesyousometimesneedtodrawtexts.Todrawatextyouhavetospecifythefonttouse.Fontscanbedefinedbycreatingfontresources(eitherintheGameMakerprogramorusingthefunctionstocreateresources).Therearedifferentfunctionstodrawtextsindifferentway.Ineachfunctionyouspecifythepositionofthetextonthescreen.Therearetwofunctionstosetthehorizontalandverticalalignmentofthetextwithrespecttothatposition.

Fortextdrawingthefollowingfunctionsexist:

draw_set_font(font)Setsthefontthatwillbeusedwhendrawingtext.Use-1tosetthedefaultfont(Arial12).draw_set_halign(halign)Setsthehorizontalalignmentusedwhendrawingtext.Chooseoneofthefollowingconstantsasvalues:

fa_left

fa_center

fa_right

draw_set_valign(valign)Setstheverticalalignmentusedwhendrawingtext.Chooseoneofthefollowingconstantsasvalues:

fa_top

fa_middle

fa_bottom

draw_text(x,y,string)Drawsthestringatposition(x,y),usingthedrawingcolorandalpha.A#symbolorcarriagereturnchr(13)orlinefeedchr(10)areinterpretedasnewlinecharacters.Inthiswayyoucandrawmulti-linetexts.(Use\#togetthe#symbolitself.)draw_text_ext(x,y,string,sep,w)Similartothepreviousroutinebutyoucanspecifytwomorethings.Firstofall,sepindicatestheseparationdistancebetweenthelinesoftextinamultilinetext.Use-1togetthedefaultdistance.Usewtoindicatethewidthofthetextinpixels.Linesthatarelongerthanthiswidtharesplit-upatspaces

Page 291: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

or-signs.Use-1tonotsplituplines.string_width(string)Widthofthestringinthecurrentfontasitwouldbedrawnusingthedraw_text()function.Canbeusedforpreciselypositioninggraphics.string_height(string)Heightofthestringinthecurrentfontasitwouldbedrawnusingthedraw_text()function.string_width_ext(string,sep,w)Widthofthestringinthecurrentfontasitwouldbedrawnusingthedraw_text_ext()function.Canbeusedforpreciselypositioninggraphics.string_height_ext(string,sep,w)Heightofthestringinthecurrentfontasitwouldbedrawnusingthedraw_text_ext()function.

Thefollowingroutinesallowyoutodrawscaledandrotatedtextandalsotousegradientcolorsontexts.ThesefunctionsareonlyavailableintheProEdition!

draw_text_transformed(x,y,string,xscale,yscale,angle)Drawsthestringatposition(x,y)inthesamewayasabove,butscaleithorizontallyandverticallywiththeindicatedfactorsandrotateitcounter-clockwiseoverangledegrees.draw_text_ext_transformed(x,y,string,sep,w,xscale,yscale,angle)

Combinesthefunctiondraw_text_extanddraw_text_transformed.Itmakesitpossibletodrawamulti-linetextrotatedandscaled.draw_text_color(x,y,string,c1,c2,c3,c4,alpha)Drawsthestringatposition(x,y)likeabove.Thefourcolorsspecifythecolorsofthetop-left,top-right,bottom-right,andbottom-leftcornerofthetext.alphaisthealphatransparencytobeused(0-1).draw_text_ext_color(x,y,string,sep,w,c1,c2,c3,c4,alpha)Similartodraw_text_ext()butwithcoloredvertices.draw_text_transformed_color(x,y,string,xscale,yscale,angle,c1,c2,c3,c4,alpha)

Similartodraw_text_transformed()butwithcoloredvertices.draw_text_ext_transformed_color(x,y,string,sep,w,xscale,yscale,angle,c1,c2,c3,c4,alpha)

Similartodraw_text_ext_transformed()butwithcoloredvertices.

Page 292: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Advanceddrawingfunctions

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Above,anumberofbasicdrawingfunctionshavebeendescribed.Hereyoufindanumberofadditionalfunctionsthatofferyoualotmorepossibilities.Firstofalltherearefunctionstodrawshapeswithgradientcolors.Secondlytherearefunctionstodrawmoregeneralpolygons,andfinallythereisthepossibilitytodrawtexturemappedpolygons.

Thefollowingextendedversionsofthebasicdrawingfunctionsexist.eachofthemgetsextracolorparametersthatareusedthedeterminethecoloratdifferentvertices.Thestandarddrawingcolorisnotusedinthesefunctions.

draw_point_color(x,y,col1)Drawsapointat(x,y)inthegivencolor.draw_line_color(x1,y1,x2,y2,col1,col2)Drawsalinefrom(x1,y1)to(x2,y2),interpolatingthecolorbetweencol1andcol2.draw_line_width_color(x1,y1,x2,y2,w,col1,col2)Drawsalinefrom(x1,y1)to(x2,y2)withwidthwinterpolatingthecolorbetweencol1andcol2.draw_rectangle_color(x1,y1,x2,y2,col1,col2,col3,col4,outline)

Drawsarectangle.Thefourcolorsindicatedthecolorsatthetop-left,top-right,bottom-right,andbottom-leftvertex.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).draw_roundrect_color(x1,y1,x2,y2,col1,col2,outline)Drawsaroundedrectangle.col1isthecolorinthemiddleandcol2thecolorattheboundary.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).draw_triangle_color(x1,y1,x2,y2,x3,y3,col1,col2,col3,outline)

Drawsatriangle.Thethreecolorsarethecolorsofthethreeverticeswhichisinterpolatedoverthetriangle.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).draw_circle_color(x,y,r,col1,col2,outline)Drawsacircleat(x,y)withradiusr.col1isthecolorinthemiddleandcol2thecoloratthe

Page 293: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

boundary.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).draw_ellipse_color(x1,y1,x2,y2,col1,col2,outline)Drawsanellipse.col1isthecolorinthemiddleandcol2thecolorattheboundary.outlineindicateswhetheronlytheoutlinemustbedrawn(true)oritshouldbefilled(false).

Youcanalsodrawlargerprimitives.Thisworksslightlydifferent.Youbeginbyspecifyingtheprimitiveyouwanttodraw.Nextyouspecifytheverticesforit,andfinallyyouendtheprimitive,atwhichmomentitisdrawn.Therearesixtypesofprimitives:

pr_pointlistTheverticesareasetofpoints.pr_linelistTheverticesareasetoflinesegments.Eachpairofverticesformsalinesegment.Sotheremustbeanevensetofvertices.pr_linestripTheverticesformapolylinewiththefirstconnectedtothesecond,thesecondtothethird,etc.Thelastoneisnotconnectedtothefirstone.Youhavetospecifyanextracopyofthefirstvertexforthis.pr_trianglelistTheverticesareasetoftriangles.Eachtripleofverticesformsatriangle.Sothenumberofverticesmustbeamultipleof3.pr_trianglestripTheverticesagainformtrianglesbutthistimeitworksslightlydifferent.Thefirstthreeformthefirsttriangle.Thelasttwoofthesevertices,togetherwiththenextvertex,formthesecondtriangle,etc.Soeachnewvertexspecifiesanewtriangle,connectedtothepreviousone.pr_trianglefanSimilartoatrianglelistbutthistimethefirstvertexispartofallthetriangles.Again,eachnewvertexspecifiesanewtriangle,connectedtothepreviousvertexandthefirstvertex.

Thefollowingfunctionsexistfordrawingprimitives

draw_primitive_begin(kind)Startaprimitiveoftheindicatedkind.draw_vertex(x,y)Addvertex(x,y)totheprimitive,usingthecolorandalphavaluesetbefore.draw_vertex_color(x,y,col,alpha)Addvertex(x,y)totheprimitive,

Page 294: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

withitsowncolorandalphavalue.Thisallowsyoutocreateprimitiveswithsmoothlychangingcolorandalphavalues.draw_primitive_end()Endthedescriptionoftheprimitive.Thisfunctionactuallydrawsit.

Finally,itispossibletodrawprimitivesusingspritesorbackgroundsastextures.Whenusingatexturetheimageisplacedontheprimitive,reshapingittofittheprimitive.Texturesareusedtoadddetailtoprimitives,e.g.abrickwall.Tousetexturesyoufirstmustobtaintheidofthetextureyouwanttouse.Forthisthefollowingfunctionsexist:

sprite_get_texture(spr,subimg)Returnstheidofthetexturecorrespondingtosubimagesubimgoftheindicatedsprite.background_get_texture(back)Returnstheidofthetexturecorrespondingtotheindicatedbackground.

Aselectedtexturemightnotyetbeinvideomemory.Thesystemwillputitthereonceyouneeditbutsometimesyouwanttodecidethisyourself.Forthisthefollowingtwofunctionsexist:

texture_preload(texid)Putsthetextureimmediatelyintovideomemory.texture_set_priority(texid,prio)Whenthereistoolittlevideomemorysomewillberemovedtemporarilytomakeroomforothersthatareneeded.Theoneswithlowestpriorityareremovedfirst.Default,allhavepriority0butyoucanchangethepriorityhere.(Usepositivevalues!)

Toaddtexturestoprimitivesyoumustspecifywhichpartsofthetexturesmustbeputwhereontheprimitive.Positionsinthetextureareindicatedwithvaluesbetween0and1butthereisaproblemhere.Sizesoftexturesmustbepowersof2(soe.g.32x32or64x64).Ifyouwanttousespritesorbackgroundastexturesyoubettermakesuretheyhavesuchasize.Ifnot,thetestwillbeblank.Tofindoutwhichpartofthetextureisactuallyusedyoucanusethefollowingtwofunctions.Theyreturnavaluebetween0and1thatindicatesthewidthorheightoftheactualpartofthetexturebeingused.Specifyingthisvalueastexturecoordinatewillindicatetherightorbottomsideofthetexture.

Page 295: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

texture_get_width(texid)Returnsthewidthofthetexturewiththegivenid.Thewidthliesintherange0-1.texture_get_height(texid)Returnstheheightofthetexturewiththegivenid.Theheightliesintherange0-1.

Todrawtexturedprimitivesyouusethefollowingfunctions:

draw_primitive_begin_texture(kind,texid)Startaprimitiveoftheindicatedkindwiththegiventexture.draw_vertex_texture(x,y,xtex,ytex)Addvertex(x,y)totheprimitivewithposition(xtex,ytex)inthetexture,blendingwiththecolorandalphavaluesetbefore.xtexandytexshouldnormallyliebetween0and1butalsolargervaluescanbeused,leadingtoarepetitionofthetexture(seebelow).draw_vertex_texture_color(x,y,xtex,ytex,col,alpha)Addvertex(x,y)totheprimitivewithposition(xtex,ytex)inthetexture,blendingwithitsowncolorandalphavalue.draw_primitive_end()Endthedescriptionoftheprimitive.Thisfunctionactuallydrawsit.

Therearethreefunctionsthatinfluencehowtexturesaredrawn:

texture_set_interpolation(linear)Indicateswhethertouselinearinterpolation(true)orpickthenearestpixel(false).Linearinterpolationgivessmoothertexturesbutcanalsobeabitblurryandsometimescostsextratime.Thissettingalsoinfluencethedrawingofspritesandbackground.Defaultisfalse.(Thiscanalsobechangedintheglobalgamesettings.)texture_set_blending(blend)Indicateswhethertouseblendingwithcolorsandalphavalues.Switchingthisoffmightbefasteronoldhardware.Thissettingalsoinfluencethedrawingofspritesandbackground.Defaultistrue.texture_set_repeat(repeat)Indicateswhethertouserepeatthetexture.Thisworksasfollows.Asindicatedabovetexturecoordinateslieintherange0-1.Ifyouspecifyavaluelargerthan1,defaulttherestisnotdrawn.Bysettingrepeattotruethetextureisrepeated.Notethatspritesandbackgroundsarealwaysdrawnwithoutrepeating.Soonceyoudrawaspriteofbackgroundthis

Page 296: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

valueisresettofalse.Defaultisfalse.

Therearetwomorefunctionthatarenotonlyusefulfordrawingtextures.Normallyprimitivesareblendedwiththebackgroundusingthealphavalue.Youcanactuallyindicatehowthismusthappen.Besidesthenormalmodeitispossibletoindicatethatthenewcolormustbeaddedtotheexistingcolororsubtractedfromtheexistingcolor.Thiscanbeusedtocreatee.g.spotlightsorshadows.Alsoitispossibletosortoftakethemaximumofthenewandexistingcolor.Thiscanavoidcertainsaturationeffectsthatyoucangetwithadding.Notethatbothsubtractingandmaximumdonottakethealphavaluefullyintoaccount.(DirectXdoesnotallowthis.)Soyoubettermakesuretheoutsideareaisblack.Therearetwofunctions.Thefirstoneonlygivesyouthefouroptionsdescribedabove.Thesecondfunctiongivesyoualotmorepossibilities.Youshouldexperimentabitwiththesettings.Ifusedeffectivelytheycanbeusedtocreatee.g.interestingexplosionorhaloeffects.

draw_set_blend_mode(mode)Indicateswhatblendmodetouse.Thefollowingvaluesarepossible:bm_normal,bm_add,bm_subtract,andbm_max.Don'tforgettoresetthemodetonormalafterusebecauseotherwisealsootherspritesandeventhebackgroundsaredrawnwiththenewblendmode.draw_set_blend_mode_ext(src,dest)Indicateswhatblendmodetouseforboththesourceanddestinationcolor.Thenewcolorissomefactortimesthesourceandanotherfactortimesthedestination.Thesefactorsaresetwiththisfunction.Tounderstandthis,thesourceanddestinationbothhaveared,green,blue,andalphacomponent.Sothesourceis(Rs,Gs,Bs,As)andthedestinationis(Rd,Gd,Bd,Ad).Allareconsideredtoliebetween0and1.Theblendfactorsyoucanchooseforsourceanddestinationare:

bm_zero:Blendfactoris(0,0,0,0).bm_one:Blendfactoris(1,1,1,1).bm_src_color:Blendfactoris(Rs,Gs,Bs,As).bm_inv_src_color:Blendfactoris(1–Rs,1–Gs,1–Bs,1–As).bm_src_alpha:Blendfactoris(As,As,As,As).bm_inv_src_alpha:Blendfactoris(1–As,1–As,1–As,1–As).bm_dest_alpha:Blendfactoris(Ad,Ad,Ad,Ad).

Page 297: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

bm_inv_dest_alpha:Blendfactoris(1–Ad,1–Ad,1–Ad,1–Ad).bm_dest_color:Blendfactoris(Rd,Gd,Bd,Ad).bm_inv_dest_color:Blendfactoris(1–Rd,1–Gd,1–Bd,1–Ad).bm_src_alpha_sat:Blendfactoris(f,f,f,1);f=min(As,1–Ad).

Forexample,thenormalblendingmodesetsthesourceblendingtobm_src_alphaandthedestinationblendingtobm_inv_src_alpha.Don'tforgettoresetthemodetonormalafterusebecauseotherwisealsootherspritesandeventhebackgroundsaredrawnwiththenewblendmode.

Drawingtextureprimitivesisabitofworkbutcanleadtogreatresults.Youcanevenuseittomakefake3Dgames.

Page 298: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

DrawingSurfaces

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Incertainsituationsyoumightwanttopaintnotdirectlyonthescreenbutonacanvasthatcanthenlaterbeusedtopaintthingsonthescreen.Suchacanvasiscalledasurface.Forexample,youwanttolettheuserdrawonthescreen.Thepaintshouldnotbedrawnonthescreen(becauseitwillberemovedeachnextstep),butinsteadyouwanttodrawitonaseparatesurfacethatiscopiedontothescreenineachstep.Oryouwanttouseatexturethatchangesovertime.

Surfacesmakethisallpossible.Theyareactuallyrathersimpletouse.Youfirstcreateasurface.Nextyouindicatethatfurtherdrawingshouldhappenonthissurface.Fromthatmomentonalldrawingfunctionsoperateonthesurface.Onceyouaredoneyouresetthedrawingtargetandfurtherdrawinghappensonthescreenagain.Youcandrawthesurfaceonthescreeninmanydifferentwaysoruseitasatexture.Therearethoughafewthingsyoumustbeawareof.Seetheremarksattheend.

Thefollowingfunctionsexisttodealwithsurfaces

surface_create(w,h)Createsasurfaceoftheindicatedwidthandheight.Returnstheidofthesurface,whichmustbeusedinallfurthercalls.Notethatthesurfacewillnotbecleared.Thisistheresponsibilityoftheuser.(Setitasatargetandcalltheappropriateclearfunction.)surface_free(id)Freesthememoryusedbythesurface.surface_exists(id)Returnswhetherthesurfacewiththeindicatedidexists.

surface_get_width(id)Returnsthewidthofthesurface.surface_get_height(id)Returnstheheightofthesurface.surface_get_texture(id)Returnsthetexturecorrespondingtothesurface.Thiscanbeusedtodrawtexturedobjectswiththeimageof

Page 299: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

thesurface.

surface_set_target(id)Setstheindicatedsurfaceasthedrawingtarget.Allsubsequentdrawinghappensonthissurface.Itresetstheprojectiontosimplycoverthesurface.surface_reset_target()Resetsthedrawingtargettothenormalscreen.

surface_getpixel(id,x,y)Returnsthecolorofthepixelcorrespondingtoposition(x,y)inthesurface.Thisisnotveryfast,sousewithcare.surface_save(id,fname)Savesapngimageofthesurfaceinthegivenfilename.Usefulformakingscreenshots.surface_save_part(id,fname,x,y,w,h)Savespartofthesurfaceinthegivenpngfilename.

draw_surface(id,x,y)Drawsthesurfaceatposition(x,y).(Withoutcolorblendingandnoalphatransparency.)draw_surface_stretched(id,x,y,w,h)Drawsthesurfacestretchedtotheindicatedregion.draw_surface_tiled(id,x,y)Drawsthesurfacetiledsothatitfillstheentireroom.draw_surface_part(id,left,top,width,height,x,y)Drawstheindicatedpartofthesurfacewithitsoriginatposition(x,y).draw_surface_ext(id,x,y,xscale,yscale,rot,color,alpha)Drawsthesurfacescaledandrotatedwithblendingcolor(usec_whitefornoblending)andtransparencyalpha(0-1).draw_surface_stretched_ext(id,x,y,w,h,color,alpha)Drawsthesurfacestretchedtotheindicatedregion.coloristheblendingcolorandalphaindicatesthetransparencysetting.draw_surface_tiled_ext(id,x,y,xscale,yscale,color,alpha)Drawsthesurfacetiledsothatitfillstheentireroombutnowwithscalefactorsandacolorandtransparencysetting.draw_surface_part_ext(id,left,top,width,height,x,y,xscale,yscale,color,alpha)

Drawstheindicatedpartofthesurfacewithitsoriginatposition(x,y)butnowwithscalefactorsandacolorandtransparencysetting.draw_surface_general(id,left,top,width,height,x,y,xscale,yscale,rot,c1,c2,c3,c4,alpha)

Page 300: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Themostgeneraldrawingfunction.Itdrawstheindicatedpartofthesurfacewithitsoriginatposition(x,y)butnowwithscalefactors,arotationangle,acolorforeachofthefourvertices(top-left,top-right,bottom-right,andbottom-left),andanalphatransparencyvalue.

surface_copy(destination,x,y,source)Copiesthesourcesurfaceatposition(x,y)inthedestinationsurface.(Withoutanyformofblending.)surface_copy_part(destination,x,y,source,xs,ys,ws,hs)Copiestheindicatedpartofthesourcesurfaceatposition(x,y)inthedestinationsurface.(Withoutanyformofblending.)

Notethattherearenofunctionstocopypartofthescreentoasurface.(Thisisimpossibleduetopossibleformatdifferencesbetweenthescreenandthesurfaces.)Ifthisisrequiredyoumustsetasurfaceasrendertargetandnextdrawtheroom.Youcanthenusethesurfacecopyingroutinestogetpartsofit.

Notethatyoucanalsocreatespritesandbackgroundsfromsurfaces.Seethesectiononchangingresourcesformoreinformation.

Somecaremustbetakenwhenusingthesefunctions.Inparticularpleasenoticethefollowing:

Youshouldneverchangethedrawingtargetwhileyouareactuallydrawingonthescreen,thatis,neveruseitindrawingevents.Thiswillcauseseriousproblemswiththeprojectionandviewport.Surfacesdonotworkcorrectlywith3Dmode.Youcanusethemwhilenotin3Dmode(bycallingd3d_end()beforeusingthem),butonceyoustart3Dmodeagainthesurfaceswillbedestroyed.Forreasonsofspeed,thesurfaceismaintainedinvideomemoryonly.Asaresult,youmightloosethesurfacewhene.g.thescreenresolutionchangesorthescreensaverpopsup.Surfaceswillnotbesavedwhensavingagame.

Page 301: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 302: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Tiles

Asyoushouldknowyoucanaddtilestorooms.Atileisapartofabackgroundresource.Tilesarejustvisibleimages.Theydonotreacttoeventsandtheydonotgeneratecollisions.Asaresult,tilesarehandledalotfasterthanobjects.Anythingthatdoesnotneedeventsorcollisionscanbestbedonethroughtiles.Also,oftenonebetterusesatileforthenicegraphicswhileasimpleobjectisusedtogeneratethecollisionevents.

Youactuallyhavemorecontrolovertilesthanyoumightthink.Youcanaddthemwhendesigningtheroombutyoucanalsoaddthemduringtherunningofthegame.Youcanchangetheirposition,andevenscalethemormakethempartiallytransparent.Atilehasthefollowingproperties:

background.Thebackgroundresourcefromwhichthetileistaken.left,top,width,height.Thepartofthebackgroundthatisused.x,y.Thepositionofthetopleftcornerofthetileintheroom.depth.Thedepthofthetile.Youcanchooseanydepthyoulike,makingtilesappearbetweenobjectinstances.visible.Whetherthetileisvisible.xscale,yscale.Eachtilecanbedrawnscaled(defaultis1).blend.Ablendingcolorusedwhendrawingthetile.alpha.Analphavalueindicatingtiletransparency.1=nottransparent,0=fullytransparent.

Tochangethepropertiesofaparticulartileyouneedtoknowitsid.Whenyouaddtileswhencreatingroomstheidisshownintheinformationbaratthebottom.Thereisalsoafunctiontofindtheidofatileataparticularposition.

Thefollowingfunctionsexistthatdealwithtiles:

tile_add(background,left,top,width,height,x,y,depth)Addsanewtiletotheroomwiththeindicatedvalues(seeabovefortheirmeaning).Thefunctionreturnstheidofthetilethatcanbeused

Page 303: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

lateron.tile_delete(id)Deletesthetilewiththegivenid.tile_exists(id)Returnswhetheratilewiththegivenidexists.

tile_get_x(id)Returnsthex-positionofthetilewiththegivenid.tile_get_y(id)Returnsthey-positionofthetilewiththegivenid.tile_get_left(id)Returnstheleftvalueofthetilewiththegivenid.tile_get_top(id)Returnsthetopvalueofthetilewiththegivenid.tile_get_width(id)Returnsthewidthofthetilewiththegivenid.tile_get_height(id)Returnstheheightofthetilewiththegivenid.tile_get_depth(id)Returnsthedepthofthetilewiththegivenid.tile_get_visible(id)Returnswhetherthetilewiththegivenidisvisible.tile_get_xscale(id)Returnsthexscaleofthetilewiththegivenid.tile_get_yscale(id)Returnstheyscaleofthetilewiththegivenid.tile_get_background(id)Returnsthebackgroundofthetilewiththegivenid.tile_get_blend(id)Returnstheblendingcolorofthetilewiththegivenid.tile_get_alpha(id)Returnsthealphavalueofthetilewiththegivenid.

tile_set_position(id,x,y)Setsthepositionofthetilewiththegivenid.tile_set_region(id,left,top,width,height)Setstheregionofthetilewiththegivenidinitsbackground.tile_set_background(id,background)Setsthebackgroundforthetilewiththegivenid.tile_set_visible(id,visible)Setswhetherthetilewiththegivenidisvisible.tile_set_depth(id,depth)Setsthedepthofthetilewiththegivenid.tile_set_scale(id,xscale,yscale)Setsthescalingofthetilewiththegivenid.tile_set_blend(id,color)Setstheblendingcolorofthetilewiththegivenid.OnlyavailableintheProEdition!tile_set_alpha(id,alpha)Setsthealphavalueofthetilewiththegivenid.

Page 304: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thefollowingfunctionsdealwithlayersoftiles,thatis,collectionsoftilesatthesamedepth.

tile_layer_hide(depth)Hidesalltilesattheindicateddepthlayer.tile_layer_show(depth)Showsalltilesattheindicateddepthlayer.tile_layer_delete(depth)Deletesalltilesattheindicateddepthlayer.tile_layer_shift(depth,x,y)Shiftsalltilesattheindicateddepthlayeroverthevectorx,y.Canbeusedtocreatescrollinglayersoftiles.tile_layer_find(depth,x,y)Returnstheidofthetilewiththegivendepthatposition(x,y).Whennotileexistsattheposition-1isreturned.Whenmultipletileswiththegivendepthexistatthepositionthefirstoneisreturned.tile_layer_delete_at(depth,x,y)Deletesthetilewiththegivendepthatposition(x,y).Whenmultipletileswiththegivendepthexistatthepositiontheyarealldeleted.tile_layer_depth(depth,newdepth)Changesthedepthofalltilesattheindicateddepthtothenewdepth.Withthisfunctionyoucanmovewholetilelayerstoanewdepth.

Page 305: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thedisplay

Thedisplayrepresentsthewholeareaonthemonitor.Ithasasize(typically1024x768,or1280x1024),acolordepth,thatis,thenumberofbitsthatareusedtorepresentasinglepixel(typically16=HighColoror32=FullColor)andarefreshfrequency,thatis,thenumberoftimespersecondthedisplayisrefreshed(typicallybetween60and120).Thesesettingscannormallybechangedthoughthedisplayproperties.Forgamesthough,inparticularwhentheyruninfull-screenmode,itisimportanttobeabletochangethesesettings.AllthesesettingscanbeinitializedforthegameintheGameSettings.Foruseduringgameplaythefollowingfunctionsexist.Notethoughthatchangingthesettingsduringgameplaywillresultinatimedelayasthingshastoberebuilt.ThefunctionstosetthemodeareonlyavailableintheProEdition.

display_get_width()Returnsthewidthofthedisplayinpixels.display_get_height()Returnstheheightofthedisplayinpixels.display_get_colordepth()Returnsthecolordepthinbits.display_get_frequency()Returnstherefreshfrequencyofthedisplay.display_set_size(w,h)Setsthewidthandheightofthedisplayinpixels.Returnswhetherthiswassuccessful.(Realizethatonlycertaincombinationsareallowed.)display_set_colordepth(coldepth)Setsthecolordepth.Ingeneralonly16and32areallowedvalues.Returnswhethersuccessful.display_set_frequency(frequency)Setstherefreshfrequencyforthedisplay.Onlyfewfrequenciesareallowed.Typicallyyoucouldsetthisto60withasameroomspeedtogetsmooth60framespersecondmotion.Returnswhethersuccessful.display_set_all(w,h,frequency,coldepth)Setsallatonce.Use-1forvaluesyoudonotwanttochange.Returnswhethersuccessful.display_test_all(w,h,frequency,coldepth)Testswhethertheindicatedsettingsareallowed.Itdoesnotchangethesettings.Use-1forvaluesyoudonotwanttochange.Returnswhetherthesettingsareallowed.

Page 306: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

display_reset()Resetsthedisplaysettingstotheoneswhentheprogramwasstarted.

Sometimesitisusefultogetinformationaboutthepositionofthemouseonthedisplayortochangethisposition.Forthisthefollowingfunctionsexist:

display_mouse_get_x()Returnsthex-coordinateofthemouseonthedisplay.display_mouse_get_y()Returnsthey-coordinateofthemouseonthedisplay.display_mouse_set(x,y)Setsthepositionofthemouseonthedisplaytotheindicatedvalues.

Page 307: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thewindow

Theactualgamehappensinawindow.Thiswindowhasanumberofproperties,likewhetherithasaborder,whetheritisfullscreen,etc.NormallythesearesetintheGameSettings.Butyoucanchangethenduringthegame.Thefollowingfunctionsexistforthis:

window_set_visible(visible)Setswhetherthegamewindowisvisible.Clearlyyounormallywantthewindowtoremainvisibleduringthewholegame.Theprogramwillnotreceivekeyboardeventswhenthewindowisinvisible.window_get_visible()Returnswhetherthegamewindowisvisible.window_set_fullscreen(full)Setswhetherthewindowisshowninfullscreenmode.window_get_fullscreen()Returnswhetherthewindowisshowninfullscreenmode.window_set_showborder(show)Setswhethertheborderaroundthewindowisshown.(Infullscreenmodeitisnevershown.)window_get_showborder()Returnswhethertheborderaroundthewindowisshowninwindowedmode.window_set_showicons(show)Setswhetherthebordericons(iconize,maximize,close)areshown.(Infullscreenmodethesearenevershown.)window_get_showicons()Returnswhetherthebordericonsareshowninwindowedmode.window_set_stayontop(stay)Setswhetherthewindowmustalwaysstayontopofotherwindows.window_get_stayontop()Returnswhetherthewindowalwaysstaysontopofotherwindows.window_set_sizeable(sizeable)Setswhetherthewindowissizeablebytheplayer.(Theplayercanonlysizeitwhentheborderisshownandthewindowisnotinfullscreenmode.)window_get_sizeable()Returnswhetherthewindowissizeablebytheplayer.window_set_caption(caption)Setsthecaptionstringforthewindow.

Page 308: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Normallyyouspecifythiswhendefiningtheroomanditcanbechangedusingthevariableroom_caption.Sothisfunctionisnormallynotuseful,unlessyoudrawtheroomyourselfratherthanlettingGameMakerdoit.Thecaptionisonlyvisiblewhenthewindowhasaborderandwhenitisnotinfullscreenmode.window_get_caption()Returnsthewindowcaption.window_set_cursor(curs)Setsthemousecursorusedinthewindow.Youcanusethefollowingconstant:

cr_default

cr_none

cr_arrow

cr_cross

cr_beam

cr_size_nesw

cr_size_ns

cr_size_nwse

cr_size_we

cr_uparrow

cr_hourglass

cr_drag

cr_nodrop

cr_hsplit

cr_vsplit

cr_multidrag

cr_sqlwait

cr_no

cr_appstart

cr_help

cr_handpoint

cr_size_all

Inparticular,tohidethemousecursor,usecr_noneasvalue.window_get_cursor()Returnsthecursorusedinthewindow.window_set_color(color)Setsthecolorofthepartofthewindowthatisnotusedfordisplayingtheroom.window_get_color()Returnsthewindowcolor.window_set_region_scale(scale,adaptwindow)Ifthewindowislargerthantheactualroomnormallytheroomisdisplayedinaregioncenteredinthewindow.Itisthoughpossibletoindicatethatitmustbescaledtofillthewholeorpartofthewindow.Avalueof1isnoscaling.Ifyouuseavalueof0theregionwillbescaledtofillthe

Page 309: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

wholewindow.Ifyousetittoanegativevalueitwillbescaledtothemaximalsizeinsidethewindowwhilemaintainingtheaspectratio(thisisoftenwhatyouwant).adaptwindowindicateswhetherthewindowsizemustbeadaptedifthescaledroomdoesnotfitin.Adaptingthewindowisonlyeffectivewhenthescalefactorispositive.window_get_region_scale()Returnsthescalefactorforthedrawingregion.

Thewindowhasapositiononthescreenandasize.(Whenwetalkaboutpositionandsizewealwaysmeantheclientpartofthewindowwithouttheborders.)Youcanchangethesealthoughyouhardlyeverdofromwithinyourgame.Normallytheyaredeterminedautomaticallyorbytheplayer.Thefollowingfunctionscanbeusedtochangethewindowpositionandsize.Notethatthesefunctionsdealwiththewindowedmode.Ifthewindowisinfullscreenmodetheycanstillbeusedbutwillonlyhaveeffectwhenswitchingfullscreenmodeoff.

window_set_position(x,y)Setsthepositionofthe(clientpartofthe)windowtotheindicatedposition.window_set_size(w,h)Setsthesizeofthe(clientpartofthe)windowtotheindicatedsize.Notethatistheindicatedsizeistoosmalltofitthedrawingregionitiskeptlargeenoughfortheregiontofitit.window_set_rectangle(x,y,w,h)Setsthepositionandsizeofthewindowrectangle.(Doesbothpreviousroutinesinonestep.)window_center()Centersthewindowonthescreen.window_default()Givesthewindowthedefaultsizeandposition(centered)onthescreen.window_get_x()Returnsthecurrentx-coordinateofthewindow.window_get_y()Returnsthecurrenty-coordinateofthewindow.window_get_width()Returnsthecurrentwidthofthewindow.window_get_height()Returnsthecurrentheightofthewindow.

Again,youprobablyneverwanttouseanyofthewindowpositioningfunctionsasGameMakertakescareoftheseautomatically.

Inrarecasesyoumightwanttoknowthepositionofthemousewithrespecttothewindow.(Normallyyoualwaysusethemousepositionwith

Page 310: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

respecttotheroomorwithrespecttoaview.)Thefollowingfunctionsexistforthis.

window_mouse_get_x()Returnsthex-coordinateofthemouseinthewindow.window_mouse_get_y()Returnsthey-coordinateofthemouseinthewindow.window_mouse_set(x,y)Setsthepositionofthemouseinthewindowtotheindicatedvalues.

Page 311: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Views

Asyoushouldknowyoucandefineuptoeightdifferentviewswhendesigningrooms.Aviewisdefinedbyitsviewareaintheroomanditsviewportonthescreen(ortobepreciseinthedrawingregionwithinthewindow).Usingviewsyoucanshowdifferentpartsoftheroomatdifferentplacesonthescreen.Also,youcanmakesurethataparticularobjectalwaysstaysvisible.

Youcancontroltheviewsfromwithincode.Youcanmakeviewsvisibleandinvisibleandchangetheplaceorsizeoftheviewsinthedrawingregionorthepositionandsizeoftheviewintheroom(whichisinparticularusefulwhenyouindicatenoobjecttobevisible).Youcanchangethesizeofthehorizontalandverticalborderaroundthevisibleobject,andyoucanindicatewhichobjectmustremainvisibleintheviews.Thelatterisveryimportantwhentheimportantobjectchangesduringthegame.Forexample,youmightchangethemaincharacterobjectbasedonitscurrentstatus.Unfortunately,thisdoesmeanthatitisnolongertheobjectthatmustremainvisible.Thiscanberemediedbyonelineofcodeinthecreationeventofallthepossiblemainobjects(assumingthismusthappeninthefirstview):

{

view_object[0]=object_index;

}

Thefollowingvariablesexistthatinfluencetheview.All,exceptthefirsttwoarearraysrangingfrom0(thefirstview)to7(thelastview).

view_enabledWhetherviewsareenabledornot.view_current*Thecurrentlydrawnview(0-7).Usethisonlyinthedrawingevent.Youcanforexamplecheckthisvariabletodrawcertainthingsinonlyoneview.Variablecannotbechanged.view_visible[0..7]Whethertheparticularviewisvisibleonthescreen.

Page 312: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

view_xview[0..7]Xpositionoftheviewintheroom.view_yview[0..7]Ypositionoftheviewintheroom.view_wview[0..7]Widthoftheviewintheroom.view_hview[0..7]Heightoftheviewintheroom.view_xport[0..7]X-positionoftheviewportinthedrawingregion.view_yport[0..7]Y-positionoftheviewportinthedrawingregion.view_wport[0..7]Widthoftheviewportinthedrawingregion.view_hport[0..7]Heightoftheviewportinthedrawingregion.view_angle[0..7]Rotationangleusedfortheviewintheroom(counter-clockwiseindegrees).view_hborder[0..7]Sizeofhorizontalborderaroundthevisibleobject(inpixels).view_vborder[0..7]Sizeofverticalborderaroundvisibleobject(inpixels).view_hspeed[0..7]Maximalhorizontalspeedoftheview.view_vspeed[0..7]Maximalverticalspeedoftheview.view_object[0..7]Objectwhoseinstancemustremainvisibleintheview.Iftherearemultipleinstancesofthisobjectonlythefirstoneisfollowed.Youcanalsoassignaninstanceidtothisvariable.Inthatcasetheparticularinstanceisfollowed.

Notethatthesizeoftheimageonthescreenisdecidedbasedonthevisibleviewsatthebeginningoftheroom.Ifyouchangeviewsduringthegame,theymightnolongerfitonthescreen.Thescreensizethoughisnotadaptedautomatically.Soifyouneedthisyouhavetodoityourself,usingthefollowingfunctions:

window_set_region_size(w,h,adaptwindow)Setthewidthandheightofthedrawingregioninthewindow.adaptwindowindicateswhetherthewindowsizemustbeadaptediftheregiondoesnotfitin.Thewindowsizewillalwaysbeadaptedifyouusefixedscaling.(Seethefunctionwindow_set_region_scale().)window_get_region_width()Returnsthecurrentwidthofthedrawingregion.window_get_region_height()Returnsthecurrentheightofthedrawingregion.

Inagameyouoftenneedthepositionofthemousecursor.Normallyyou

Page 313: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

useforthisthevariablesmouse_xandmouse_y.Whentherearemultipleviews,thesevariablesgivethemousepositionwithrespecttotheviewthemouseisin.Sometimesthough,youmightneedthemousepositionwithrespecttoaparticularview,alsowhenitisoutsidethatview.Forthisthefollowingfunctionsexist.

window_view_mouse_get_x(id)Returnsthex-coordinateofthemousewithrespecttotheviewwithindexid.window_view_mouse_get_y(id)Returnsthey-coordinateofthemousewithrespecttotheviewwithindexid.window_view_mouse_set(id,x,y)Setsthepositionofthemousewithrespecttotheviewwithindexid.window_views_mouse_get_x()Returnsthex-coordinateofthemousewithrespecttotheviewitisin(sameasmouse_x).window_views_mouse_get_y()Returnsthey-coordinateofthemousewithrespecttotheviewitisin(sameasmouse_y).window_views_mouse_set(x,y)Setsthepositionofthemousewithrespecttothefirstviewthatisvisible.

Page 314: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Repaintingthescreen

Normallyattheendofeachsteptheroomisrepaintedonthescreen.Butinrarecircumstancesyouneedtorepainttheroomatothermoments.Thishappenswhenyourprogramtakesoverthecontrol.Forexample,beforesleepingalongtimearepaintmightbewanted.Also,whenyourcodedisplaysamessageandwantstowaitfortheplayertopressakey,youneedarepaintinbetween.Therearetwodifferentroutinestodothis.

screen_redraw()Redrawstheroombycallingalldrawevents.screen_refresh()Refreshesthescreenusingthecurrentroomimage(notperformingdrawingevents).

Tounderstandthesecondfunction,youwillneedtounderstandmorefullyhowdrawingworksinternally.Thereisinternallyanimageonwhichalldrawinghappens.Thisimageisnotvisibleonthescreen.Onlyattheendofastep,afteralldrawinghastakenplace,isthescreenimagereplacedbythisinternalimage.(Thisiscalleddoublebuffering.)Thefirstfunctionredrawstheinternalimageandthenrefreshesthescreenimage.Thesecondfunctiononlyrefreshestheimageonthescreen.

Nowyoushouldalsorealizewhyyoucannotusedrawingactionsorfunctionsinothereventsthandrawingevents.Theywilldrawthingsontheinternalimagebutthesewon'tbevisibleonthescreen.Andwhenthedrawingeventsareperformed,firsttheroombackgroundisdrawn,erasingallyoudrewontheinternalimage.Butwhenyouusescreen_refresh()afteryourdrawing,theupdatedimagewillbecomevisibleonthescreen.So,forexample,ascriptcandrawsometextonthescreen,calltherefreshfunctionandthenwaitfortheplayertopressakey,likeinthefollowingpieceofcode.

{

draw_text(room_width/2,100,'Pressanykeytocontinue.');

screen_refresh();

keyboard_wait();

}

Page 315: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Pleaserealizethat,whenyoudrawinanothereventthanthedrawingevent,youdrawsimplyontheimage,notinaview!Sothecoordinatesyouusearethesameasiftherearenoviews.Becarefulwhenusingthistechnique.Makesureyouunderstanditfirstandrealizethatrefreshingthescreentakessometime.

WhenyouaredrawingtheroomyourselfitcanbeusefultoNOTletitbedrawnautomaticatall.Forexample,youmightwanttodrawtheroomonlyevery5steps.Youcanusethefollowingfunctionsforthis:

set_automatic_draw(value)Indicateswhethertoautomaticallyredrawtheroom(true,default)ornot(false).

Finallythereisafunctionwithwhichyoucansetwhethertosynchronizethedrawingwiththerefreshfrequencyofthemonitor:

set_synchronization(value)Indicateswhethertosynchronizethedrawingwiththerefreshfrequencyofthemonitor.

Youcanalsoforceawaitforthenextverticalsynchronizationusingthefollowingfunction:

screen_wait_vsync()Waitsforthenextverticalsynchronizationofthemonitor.

Page 316: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Soundandmusic

Soundplaysacrucialroleincomputergames.Soundsareaddedtoyourgameintheformofsoundresources.Makesurethatthenamesyouusearevalidvariablenames.Asyouwillhaveseenyoucanindicatefourdifferenttypesofsound:normalsounds,backgroundmusic,3Dsounds,andsoundsthatmustbeplayedthroughthemediaplayer.

Normalsoundsareusedforsoundeffects.Ingeneralwavefilesareusedforthis.Manyofthemcanplayatthesamemoment(evenmultipleinstancesofthesamenormalsound).Youcanapplyallsortsofeffectstothem.

Backgroundmusictypicallyconsistofmidifilesbutsometimesalsowavefilesareused.Soundeffectscanbeappliedtoit.Theonlydifferencewithnormalsoundsisthatonlyonebackgroundmusiccanplayatanymoment.Ifyoustartonethecurrentoneisstopped.

3Dsoundsallowfor3Dsoundeffectswhichisdescribedbelow.Theyaremonosounds(waveormidi).

Finally,ifyouwanttouseanothersoundtype,inparticularmp3,thesecannotbeplayedthroughDirectX.Asaresultthenormalmediaplayermustbeusedforthis.Thisismuchmorelimited.Onlyonesoundcanplayatthesametime.Noeffectscanbeapplied(notevenvolumechanges)andthetimingfore.g.loopingsoundsispoor.Therecanalsobedelaysinplayingthesesounds.Youarestronglyencouragednottousethem.(Somecomputersmightalsonotsupportthem)

Informationonsoundandmusiccanbefoundinthefollowingpages:

BasicsoundfunctionsSpecialeffects3DmusicCDmusic

Page 317: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 318: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Basicsoundfunctions

Therearefivebasicfunctionsrelatedtosounds,twotoplayasound,onetocheckwhetherasoundisplaying,andtwotostopsounds.Mosttaketheindexofthesoundasargument.Thenameofthesoundrepresentsitsindex.Butyoucanalsostoretheindexinavariable,andusethat.

sound_play(index)Playstheindicatessoundonce.Ifthesoundisbackgroundmusicthecurrentbackgroundmusicisstopped.sound_loop(index)Playstheindicatessound,loopingcontinuously.Ifthesoundisbackgroundmusicthecurrentbackgroundmusicisstopped.sound_stop(index)Stopstheindicatessound.Iftherearemultiplesoundswiththisindexplayingsimultaneously,allwillbestopped.sound_stop_all()Stopsallsounds.sound_isplaying(index)Returnswhether(acopyof)theindicatedsoundisplaying.Notethatthisfunctionsreturnstruewhenthesoundactuallyplaysthroughthespeakers.Afteryoucallthefunctiontoplayasounditdoesnotimmediatelyreachthespeakerssothefunctionmightstillreturnfalseforawhile.Similar,whenthesoundisstoppedyoustillhearitforawhile(e.g.becauseofecho)andthefunctionwillstillreturntrue.

Itispossibletousefurthersoundeffects.Inparticularyoucanchangethevolumeandthepan,thatis,whetherthesoundcomesfromtheleftorrightspeaker.Inallthesecasesthevolumecanonlybereduced.Thesefunctionsdonotworkforfilesthatplaythroughthemediaplayer(likemp3files).

sound_volume(index,value)Changesthevolumefortheindicatedsound(0=low,1=high).sound_global_volume(value)Changestheglobalvolumeforallsounds(0=low,1=high).sound_fade(index,value,time)Changesthevolumefortheindicatedsoundtothenewvalue(0=low,1=high)duringtheindicatedtime(inmilliseconds).Thiscanbeusedtofadeoutorfadeinmusic.

Page 319: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

sound_pan(index,value)Changesthepanfortheindicatedsound(-1=left,0=center,1=right).sound_background_tempo(factor)Changesthetempoofthebackgroundmusic(ifitisamidifile).factorindicatesthefactorwithwhichtomultiplythetempo.Soavalueof1correspondstothenormaltempo.Largervaluescorrespondtoafastertempo,smallervaluestoaslowertempo.Mustliebetween0.01and100.

Besidesmidiandwavefiles(andmp3file)thereisactuallyafourthtypeoffilethatcanbeplayed:directmusicfiles.Thesehavetheextension.sgt.Suchfilesthoughoftenrefertootherfilesdescribinge.g.bandorstyleinformation.Tofindthesefiles,thesoundsystemmustknowwheretheyarelocated.Tothisendyoucanusethefollowingfunctionstosetthesearchdirectoryforfiles.Notethoughthatyoumustaddthefilesyourself.GameMakerdoesnotautomaticallyincludesuchadditionalfiles.

sound_set_search_directory(dir)Setsthedirectoryinwhichdirectmusicfilesaretobefound.Thedirstringshouldnotinclucethefinalbackslash.

Page 320: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Soundeffects

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Soundeffectscanbeusedtochangethewaysoundsandbackgroundmusicsounds.Realizethatsoundeffectsonlyapplytowavefilesandmidifiles,nottomp3files.Thissectiondescribesthefunctionsthatexistforusingandchangingsoundeffects.Realizethattousethesefunctionsyouneedtohaveagoodunderstandingofhowsoundandsynthesizerswork.Noexplanationofthedifferentparametersisgivenhere.Searchtheweborbooksforfurtherinformations.

Toapplyasoundeffecttoaparticularsoundyoucaneitherindicatethiswhendefiningthesoundresourceoryoucanusethefollowingfunction

sound_effect_set(snd,effect)Setsa(combinationof)soundeffect(s)fortheindicatedsound.effectcanbeanyofthefollowingvalues:

se_nonese_chorusse_echo

se_flanger

se_gargle

se_reverb

se_compressor

se_equalizer

Youcansetacombinationofeffectsbyaddingupthevalues.Soe.g.youcanuse

sound_effect_set(snd,se_echo+se_reverb);

togetacombinationofechoandreverbeffects.

Alleffectshavesomedefaultsettings.Youcanchangethesesettingsonceaneffecthasbeenappliedtoasound.Theorderhereiscrucial.Youfirstapplytheeffecttothesoundandnextsettheparametersforit.

Page 321: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Onceyoureapplyeffectstothesound,thesettingsaregoneandyouhavetosetthemagain.Notethatallparametersmustlieinaparticularrange,whichisindicatedbelow.Thefollowingfunctionsexistforchangingeffectparameters:

sound_effect_chorus(snd,wetdry,depth,feedback,frequency,wave,delay,phase)

Setstheparametersforthechoruseffectfortheindicatedsound.Thefollowingparameterscanbeset:

wetdryRatioofwet(processed)signaltodry(unprocessed)signal.(range:0to100,default50)depthPercentagebywhichthedelaytimeismodulatedbythelow-frequencyoscillator,inhundredthsofapercentagepoint.(range:0to100,default25)feedbackPercentageofoutputsignaltofeedbackintotheeffect'sinput.(range:-99to99,default0)frequencyFrequencyoftheLFO.(range:0to10,default0)waveWaveformoftheLFO.(0=triangle,1=wave,default1)delayNumberofmillisecondstheinputisdelayedbeforeitisplayedback.(range:0to20,default0)phasePhasedifferentialbetweenleftandrightLFOs.(range:0to4,default2)

sound_effect_echo(snd,wetdry,feedback,leftdelay,rightdelay,pandelay)

Setstheparametersfortheechoeffectfortheindicatedsound.Thefollowingparameterscanbeset:

wetdryRatioofwet(processed)signaltodry(unprocessed)signal.(range:0to100,default50)feedbackPercentagefedbackintoinput(range:0to100,default0)leftdelayDelayforleftchannel,inmilliseconds.(range:1to2000,default333)rightdelayDelayforrightchannel,inmilliseconds.(range:1to2000,default333)pandelayWhethertoswapleftandrightdelayswitheachsuccessiveecho.(0=don'tswap,1=swap,default0)

Page 322: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

sound_effect_flanger(snd,wetdry,depth,feedback,frequency,wave,delay,phase)

Setstheparametersfortheflangereffectfortheindicatedsound.Thefollowingparameterscanbeset:

wetdryRatioofwet(processed)signaltodry(unprocessed)signal.(range:0to100,default50)depthPercentagebywhichthedelaytimeismodulatedbythelow-frequencyoscillator,inhundredthsofapercentagepoint.(range:0to100,default25)feedbackPercentageofoutputsignaltofeedbackintotheeffect'sinput.(range:-99to99,default0)frequencyFrequencyoftheLFO.(range:0to10,default0)waveWaveformoftheLFO.(0=triangle,1=wave,default1)delayNumberofmillisecondstheinputisdelayedbeforeitisplayedback.(range:0to20,default0)phasePhasedifferentialbetweenleftandrightLFOs.(range:0to4,default2)

sound_effect_gargle(snd,rate,wave)Setstheparametersforthegargleeffectfortheindicatedsound.Thefollowingparameterscanbeset:

rateRateofmodulation,inHertz.(range:1to1000,default1)waveShapeofthemodulationwave.(0=triangle,1=square,default0)

sound_effect_reverb(snd,gain,mix,time,ratio)Setstheparametersforthereverbeffectfortheindicatedsound.Thefollowingparameterscanbeset:

gainInputgainofsignal,indecibels(dB).(range:-96to0,default0)mixReverbmix,indB.(range:-96to0,default0)timeReverbtime,inmilliseconds.(range:0.001to3000,default1000)ratioFrequencyratio.(range:0.001to0.999,default0.001)

sound_effect_compressor(snd,gain,attack,release,threshold,ratio,delay)

Page 323: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Setstheparametersforthecompressoreffectfortheindicatedsound.Thefollowingparameterscanbeset:

gainOutputgainofsignalaftercompression.(range:-60to60,default0)attackTimebeforecompressionreachesitsfullvalue.(range:0.01to500,default0.01)releaseSpeedatwhichcompressionisstoppedafterinputdropsbelowthreshold.(range:50to3000,default50)thresholdPointatwhichcompressionbegins,indecibels.(range:-60to0,default-10)ratioCompressionratio.(range:1to100,default10)delayTimeafterthresholdisreachedbeforeattackphaseisstarted,inmilliseconds.(range:0to4,default0)

sound_effect_equalizer(snd,center,bandwidth,gain)Setstheparametersfortheequalizereffectfortheindicatedsound.Thefollowingparameterscanbeset:

centerCenterfrequency,inhertz.(range:80to16000)bandwidthBandwidth,insemitones.(range:1to36)gainGain.(range:-15to15)

Page 324: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

3Dsound

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

3Dsoundsreferstosoundthathasaposition(andvelocity)withrespecttothelistener.Althoughitsmostprominentuseisin3Dgamesyoucanalsoeffectivelyuseitin2Dgames.Theideaisthatasoundhasapositioninspace.Inallfunctionsthelistenerisassumedtobeatposition(0,0,0).Thesystemcalculateshowthelistenerwouldhearthesoundandadaptitaccordingly.Theeffectisespeciallygoodwhenyouhaveagoodspeakersystembutisalreadyworksonsmallspeakers.

Besidesaposition,thesoundcanalsohasavelocity.Thisleadstowell-knowndopplereffectswhicharecorrectlymodelled.Finallythesoundcanhaveanorientationand,again,thesoundisadaptedaccordingly.

GameMakersupports3Dsoundoptionsthroughthefunctionsbelow.Theyonlyworkforsoundresourcesthatwereindicatedtobe3D.(Thedisadvantageisthat3Dsoundswillbemono,notstereo.)

sound_3d_set_sound_position(snd,x,y,z)Setsthepositionoftheindicatedsoundwithrespecttothelistenertotheindicatedpositioninspace.Valuesonthex-axisincreasefromlefttoright,onthey-axisfromdowntoup,andonthez-axisfromneartofar.Thevaluesaremeasuredinmeters.Thevolumewithwhichthesoundishearddependsonthismeasureinthesamewayasintherealworld.sound_3d_set_sound_velocity(snd,x,y,z)Setsthevelocityoftheindicatedsoundtotheindicatedvectorinspace.Pleasenotethatsettingthevelocitydoesnotmeanthatthepositionchanges.Thevelocityisonlyusedforcalculatingdopplereffects.Soifyouwanttomovethesoundyoumustyourselfchangethepositionofthesound.sound_3d_set_sound_distance(snd,mindist,maxdist)Setstheminimumdistanceatwhichthesounddoesnolongerincreaseinloudnessandthemaximumdistanceatwhichthesoundcannolongerbeheard.Sowhenthedistanceliesbetween0andtheminimumdistancethesoundisatmaximalamplitude.When

Page 325: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

betweentheminimaldistanceandthemaximaldistancetheamplitudeslowlydecreasesuntileitherthemaximaldistanceisreachedorthesoundisanywaynolongeraudible.Defaulttheminimumdistanceis1meterandthemaximaldistanceis1billionmeters.sound_3d_set_sound_cone(snd,x,y,z,anglein,angleout,voloutside)

Normallysoundhasthesameamplitudeatagivendistanceinalldirections.Youcansetthesoundconetochangethisandmakesounddirectional.x,y,zspecifythedirectionofthesoundcone.angleinspecifiestheinsideangle.Ifthelistenerisinsidethisangleithearsthesoundatitsnormalvolume.angleoutspecifiestheoutsideangle.Whenthelistenerisoutsidethisthevolumeisindicatedwithvoloutside.Tobeprecise,voloutsideisanegativenumberthatindicatesthenumberofhundredsofdecibelthatmustbesubtractedfromtheinsidevolume.Betweentheinsideandoutsideanglethevolumegraduallydecreases.

Page 326: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

CDmusic

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

TherearealsoanumberoffunctionsdealingwithplayingmusicfromaCD.

cd_init()Mustbecalledbeforeusingtheotherfunctions.ShouldalsobecalledwhenaCDischanged(orsimplyfromtimetotime).cd_present()ReturnswhetheraCDispresentinthedefaultCDdrive.cd_number()ReturnsthenumberoftracksontheCD.cd_playing()ReturnswhethertheCDisplaying.cd_paused()ReturnswhethertheCDispausedorstopped.cd_track()Returnsthenumberofthecurrenttrack(1=thefirst).cd_length()ReturnsthelengthofthetotalCDinmilliseconds.cd_track_length(n)ReturnsthelengthoftracknoftheCDinmilliseconds.cd_position()ReturnsthecurrentpositionontheCDinmilliseconds.cd_track_position()Returnsthecurrentpositioninthetrackbeingplayedinmilliseconds.cd_play(first,last)TellstheCDtoplaytracksfirstuntillast.IfyouwanttoplaythefullCDgive1and1000asarguments.cd_stop()Stopsplaying.cd_pause()Pausestheplaying.cd_resume()Resumestheplaying.cd_set_position(pos)SetsthepositionontheCDinmilliseconds.cd_set_track_position(pos)Setsthepositioninthecurrenttrackinmilliseconds.cd_open_door()OpensthedooroftheCDplayer.cd_close_door()ClosesthedooroftheCDplayer.

Thereisoneverygeneralfunctiontoaccessthemultimediafunctionalityofwindows.

Page 327: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

MCI_command(str)ThisfunctionssendsthecommandstringtotheWindowsmultimediasystemusingtheMediaControlInterface(MCI).Itreturnsthereturnstring.Youcanusethistocontrolallsortsofmultimediadevices.SeetheWindowsdocumentationforinformationinhowtousethiscommand.ForexampleMCI_command('playcdaudiofrom1')playsaCD(afteryouhavecorrectlyinitializeditusingothercommands).Thisfunctionisonlyforadvanceduse!

Page 328: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Splashscreens,highscores,andotherpop-ups

Inthissectionwewilldescribeanumberoffunctionsthatcanbeusedtodisplaysplashscreenswithvideos,images,etc.,todisplaymessagesandaskquestionstotheplayer,andtoshowthehighscorelist.

Informationonsplashscreenandmessagescanbefoundinthefollowingpages:

SplashScreensPopupMessagesandQuestionsHighscoreList

Page 329: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Splashscreens

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Manygameshaveso-calledsplashscreens.Thesescreensshowavideo,animage,orsometext.Oftentheyareusedatthebeginningofthegame(asanintro),thebeginningofalevel,orattheendofthegame(forexamplethecredits).InGameMakersuchsplashscreenswithtext,imagesorvideocanbeshownatanymomentduringthegame.

Defaultthesesplashscreensareshowninsidethegamewindow,butitisalsopossibletoshowtheminaseparatewindow.Thegameisinterruptedwhilethesplashscreenisshown.Theplayercanreturntothegamebypressingtheescapekeyorbyclickingwiththemouseinthewindow.(Thesesettingscanbechanged;seebelow.)

Thefollowingfunctionscanbeusedtodisplaythesplashscreens:

splash_show_video(fname,loop)Showsavideosplashscreen.fnameisthenameofthevideofile.Whetheraparticularmoviefileissupporteddependsonthedriversonthemachine.Typicallyyoucanuse.avi,.mpg,and.wmvfilesbutavoidspecialcodecs.Youbestputthisfileinthefolderofthegameyourselforinasubfolder.loopindicateswhethertoloopthevideo.splash_show_text(fname,delay)Showsatextsplashscreen.fnameisthenameofthetextfile.Youcaneitherdisplaystandardtextfiles(.txt)orrichtextfiles(.rtf).Onlypartoftherichtextfeaturesaretakenintoaccount.E.g.imagesandotherembeddedobjectsarenotshown.delayindicatesthedelayinmillisecondsbeforereturningtothegame.use0oranegativevaluetowaituntiltheplayerpressestheescapekeyorclickswiththemouseinthewindow.(Notethatnoscrollbarwillbeshownnoristhereanotherwaytoscrollthetext.Sothetextmustfitthewindow.)splash_show_image(fname,delay)Showsanimagesplashscreen.fnameisthenameoftheimagefile.Manyimagetypesaresupported(forexample.bmp,.jpg,.tif,and.wmf)butnoanimated

Page 330: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

images.delayisthedelayinmillisecondsbeforereturningtothegame.splash_show_web(url,delay)Showsawebpagesplashscreen.urlistheurlofthewebpage(startingwithhttp://)oritisthefilenameforalocalhtmlfile.Notehoweverthatyoumustprovidethefullpathforthistowork.Soyoubeste.g.useasurlsomethinglikeworking_directory+"\index.html".delayisthedelayinmillisecondsbeforereturningtothegame.

Youcanchangethewaythesplashscreensaredisplayedusingthefunctionsbelow:

splash_set_main(main)Indicatedwhetherthesplashscreenmustbeshowninthemaingamewindow(true,default)orinaseparatewindow(false).splash_set_scale(scale)Setsthescalefactortobeusedwhendisplayingasplashvideoorimage.Whenusingavalueof0thescalefactorischosensuchthatthewindowisfilled(default).splash_set_cursor(vis)Setswhetherthecursorshouldbevisibleinthesplashscreen.Defaultitisvisible.Formoviesthecursorcannotbeswitchedoff.splash_set_color(col)Setsthecoloroftheareasurroundingtheimageorvideo.splash_set_caption(cap)Setsthecaptionforthesplashwindow.Thisonlyhaseffectwhenisaseparatesplashwindowisused.Defaulttheemptystringisused.splash_set_fullscreen(full)Indicateswhethertouseafullscreenwindowornot.Thisonlyhaseffectwhenisaseparatesplashwindowisused.Defaultanormalwindowisused.splash_set_border(border)Indicateswhetherthewindowshouldhaveaborder.Thisonlyhaseffectwhenisaseparatenormalsplashwindowisused.Defaultaborderisused.splash_set_size(w,h)Setsthesizeofthesplashwindow.Thisonlyhaseffectwhenisaseparatenormalsplashwindowisused.Defaultsizeis640x480.splash_set_position(x,y)Setsthepositionofthesplashwindow.Thisonlyhaseffectwhenisaseparatenormalsplashwindowis

Page 331: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

used.DefaultWindowsdeterminestheposition.splash_set_adapt(adapt)Indicatedwhetherthesizeofthewindowmustbeadaptedtothescaledsizeofthevideoorimage.Thisonlyhaseffectwhenisaseparatesplashwindowisused.Defaultadaptistrue.splash_set_top(top)Indicateswhetherthewindowshouldstayontopofotherwindows.Thisonlyhaseffectwhenisaseparatesplashwindowisused.Defaultthevalueistrue.splash_set_interrupt(interrupt)Indicateswhetherthegameplayshouldbeinterruptedwhileshowingthesplashwindow.Thisonlyhaseffectwhenisaseparatesplashwindowisused.Defaultthevalueistrue.splash_set_stop_key(stop)IndicateswhethertostopthedisplayofthesplashscreenwhentheplayerpressedtheEscapekey.Defaultthevalueistrue.splash_set_stop_mouse(stop)Indicateswhethertostopthedisplayofthesplashscreenwhentheplayerpressedthemouseinsidethesplashscreen.Defaultthevalueistrue.splash_set_close_button(show)Indicateswhethertoshowaclosebuttoninthetoprightcornerofthesplashscreen.Thisisusefulwhenrunninggamesinfullscreenmodeorwithoutaborder.Defaultthevalueistrue.

Thereisoneparticulartypeofsplashinfo,whichisthegameinformationthattheusercanenterinGameMaker.Youcandisplayitusingthefollowingfunction.Youcanalsoloadaseparateinfofile.Thisiscloselyrelatedtothedisplayingofthetextsplashscreenbutthedisplayisgovernedbythesettingsprovidedwhendefiningthegameinformationandnotbythesettingsabove.Itisalsodisplayedinadifferentwindow,soitispossibletodisplayboththegameinformationandasplashscreenatthesamemoment.ThesefunctionsalsoworkintheLiteEdition.

show_info()Displaysthegameinformationwindow.load_info(fname)Loadsthegameinformationfromthefilenamedfname.Thisshouldbearichtextfile(.rtf).Thismakesitpossibletoshowdifferenthelpfilesatdifferentmoments.Notethatcontrarytothespashscreens,thisrtffilecannotcontainimages.

Page 332: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 333: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Pop-upmessagesandquestions

Anumberofotherfunctionsexisttopopupmessages,questions,amenuwithchoices,oradialoginwhichtheplayercanenteranumber,astring,orindicateacolororfilename:

show_message(str)Displaysadialogboxwiththestringasamessage.show_message_ext(str,but1,but2,but3)Displaysadialogboxwiththestringasamessageanduptothreebuttons.But1,but2andbut3containthebuttontext.Anemptystringmeansthatthebuttonisnotshown.Inthetextsyoucanusethe&symboltoindicatethatthenextcharactershouldbeusedasthekeyboardshortcutforthisbutton.Thefunctionreturnsthenumberofthebuttonpressed(0iftheuserpressestheEsckey).show_question(str)Displaysaquestion;returnstruewhentheuserselectsyesandfalseotherwise.get_integer(str,def)Askstheplayerinadialogboxforanumber.stristhemessage.defisthedefaultnumbershown.get_string(str,def)Askstheplayerinadialogboxforastring.stristhemessage.defisthedefaultvalueshown.message_background(back)Setsthebackgroundimageforthepop-upboxforanyofthefunctionsabove.backmustbeoneofthebackgroundsdefinedinthegame.Unfortunately,alphavaluesarenottakenintoaccount.However,iftheleft-bottompixelhasanalphavalueof0,allpixelswiththatcolorwillbeconsideredtransparent.message_alpha(alpha)Setsthealphatranslucenceforthepop-upboxforanyofthefunctionsabove.alphamustliebetween0(completelytranslucent)and1(nottranslucent)(onlyforWindows2000orlater).message_button(spr)Setsthespriteusedforthebuttonsinthepop-upbox.sprmustbeaspriteconsistingofthreeimages,thefirstindicatesthebuttonwhenitisnotpressedandthemouseisfaraway,thesecondindicatesthebuttonwhenthemouseisaboveitbutnotpressedandthethirdisthebuttonwhenitispressed.

Page 334: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Unfortunately,alphavaluesarenottakenintoaccount.However,iftheleft-bottompixelhasanalphavalueof0,allpixelswiththatcolorwillbeconsideredtransparent.message_text_font(name,size,color,style)Setsthefontforthetextinthepop-upbox.(ThisisanormalWindowsfont,notoneofthefontresourcesyoucanoutinyourgame!)styleindicatesthefontstyle(0=normal,1=bold,2=italic,and3=bold-italic).message_button_font(name,size,color,style)Setsthefontforthebuttonsinthepop-upbox.styleindicatesthefontstyle(0=normal,1=bold,2=italic,and3=bold-italic).message_input_font(name,size,color,style)Setsthefontfortheinputfieldinthepop-upbox.styleindicatesthefontstyle(0=normal,1=bold,2=italic,and3=bold-italic).message_mouse_color(col)Setsthecolorofthefontforthebuttonsinthepop-upboxwhenthemouseisaboveit.message_input_color(col)Setsthecolorforthebackgroundoftheinputfiledinthepop-upbox.message_caption(show,str)Setsthecaptionforthepop-upbox.showindicateswhetherabordermustbeshown(1)ornot(0)andstrindicatesthecaptionwhentheborderisshown.message_position(x,y)Setsthepositionofthepop-upboxonthescreen.Use-1,-1tocenterthebox.message_size(w,h)Fixesthesizeofthepop-upboxonthescreen.Ifyouchoose-1forthewidththewidthoftheimageisused.Ifyouchoose-1fortheheighttheheightiscalculatedbasedonthenumberoflinesinthemessage.show_menu(str,def)Showsapopupmenu.strindicatesthemenutext.Thisconsistsofthedifferentmenuitemswithaverticalbarbetweenthem.Forexample,str='menu0|menu1|menu2'.Whenthefirstitemisselecteda0isreturned,etc.Whentheplayerselectsnoitem,thedefaultvaluedefisreturned.show_menu_pos(x,y,str,def)Showsapopupmenuasinthepreviousfunctionbutatpositionx,yonthescreen.get_color(defcol)Askstheplayerforacolor.defcolisthedefaultcolor.IftheuserpressesCancelthevalue-1isreturned.get_open_filename(filter,fname)Askstheplayerforafilenametoopenwiththegivenfilter.Thefilterhastheform

Page 335: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

'name1|mask1|name2|mask2|...'.Amaskcontainsthedifferentoptionswithasemicolonbetweenthem.*meansanystring.Forexample:'bitmaps|*.bmp;*.wmf'.IftheuserpressesCancelanempystringisreturned.get_save_filename(filter,fname)Asksforafilenametosavewiththegivenfilter.IftheuserpressesCancelanempystringisreturned.get_directory(dname)Asksforadirectory.dnameisthedefaultname.IftheuserpressesCancelanempystringisreturned.get_directory_alt(capt,root)Analternativewaytoaskforadirectory.captisthecaptiontobeshow.rootistherootofthedirectorytreetobeshown.Usetheemptystringtoshowthewholetree.IftheuserpressesCancelanempystringisreturned.show_error(str,abort)Displaysastandarderrormessage(and/orwritesittothelogfile).abortindicateswhetherthegameshouldabort.

Page 336: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Highscorelist

Onespecialpop-upisthehighscorelistthatismaintainedforeachgame.Thefollowingfunctionsexist:

highscore_show(numb)Showsthehighscoretable.numbisthenewscore.Ifthisscoreisgoodenoughtobeaddedtothelist,theplayercaninputaname.Use-1tosimpledisplaythecurrentlist.highscore_set_background(back)Setsthebackgroundimagetouse.backmustbetheindexofoneofthebackgroundresources.highscore_set_border(show)Setswhetherthehighscoreformmusthaveaborderornot.highscore_set_font(name,size,style)Setsthefontusedforthetextinthetable.(ThisisanormalWindowsfont,notoneofthefontresources.)Youspecifythename,sizeandstyle(0=normal,1=bold,2=italic,3=bold-italic).highscore_set_colors(back,new,other)Setsthecolorsusedforthebackground,thenewentryinthetable,andtheotherentries.highscore_set_strings(caption,nobody,escape)Changesthedifferentdefaultstringsusedwhenshowingthehighscoretable.captionisthecaptionoftheform.nobodyisthestringusedwhenthereisnobodyattheparticularrank.escapeisthestringatthebottomindicatingtopresstheescapekey.Youcaninparticularusethiswhenyourgameshoulduseadifferentlanguage.highscore_show_ext(numb,back,border,col1,col2,name,size)Showsthehighscoretablewithanumberofoptions(canalsobeachievedbyusinganumberofthepreviousfunctions).numbisthenewscore.Ifthisscoreisgoodenoughtobeaddedtothelist,theplayercaninputaname.Use-1tosimpledisplaythecurrentlist.backisthebackgroundimagetouse,borderindicateswhetherornottoshowtheborder.col1isthecolorforthenewentry,col2thecolorfortheotherentries.nameisthenameofthefonttouse,andsizeisthefontsize.highscore_clear()Clearsthehighscorelist.highscore_add(str,numb)Addsaplayerwithnamestrandscore

Page 337: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

numbtothelist.highscore_add_current()Addsthecurrentscoretothehighscorelist.Theplayerisaskedtoprovideaname.highscore_value(place)Returnsthescoreofthepersononthegivenplace(1-10).Thiscanbeusedtodrawyourownhighscorelist.highscore_name(place)Returnsthenameofthepersononthegivenplace(1-10).draw_highscore(x1,y1,x2,y2)Drawsthehighscoretableintheroomintheindicatedbox,usingthecurrentfont.

Page 338: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Resources

InGameMakeryoucandefinevarioustypesofresources,likesprites,sounds,fonts,objects,etc.Inthischapteryouwillfindanumberoffunctionsthatgiveinformationabouttheresources.Inthenextchapteryoufindinformationonhowtomodifyandcreateresourcesonthefly.

Informationonresourcescanbefoundinthefollowingpages:

SpritesSoundsBackgroundsFontsPathsScriptsTimelinesObjectsRooms

Page 339: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Sprites

Thefollowingfunctionswillgiveyouinformationaboutasprite:

sprite_exists(ind)Returnswhetheraspritewiththegivenindexexists.sprite_get_name(ind)Returnsthenameofthespritewiththegivenindex.sprite_get_number(ind)Returnsthenumberofsubimagesofthespritewiththegivenindex.sprite_get_width(ind)Returnsthewidthofthespritewiththegivenindex.sprite_get_height(ind)Returnstheheightofthespritewiththegivenindex.sprite_get_xoffset(ind)Returnsthex-offsetofthespritewiththegivenindex.sprite_get_yoffset(ind)Returnsthey-offsetofthespritewiththegivenindex.sprite_get_bbox_left(ind)Returnstheleftsideoftheboundingboxofthespritewiththegivenindex.sprite_get_bbox_right(ind)Returnstherightsideoftheboundingboxofthespritewiththegivenindex.sprite_get_bbox_top(ind)Returnsthetopsideoftheboundingboxofthespritewiththegivenindex.sprite_get_bbox_bottom(ind)Returnsthebottomsideoftheboundingboxofthespritewiththegivenindex.

Incertainsituationsyoumightwanttosavethebitmapcorrespondingtoaparticularsubimageofthespritetoafile.Forthisthefollowingfunctionscanbeused:

sprite_save(ind,subimg,fname)Savessubimagesubimgofspriteindtothefilewiththenamefname.Thismustbea.pngfile.OnlyavailableintheProEdition.sprite_save_strip(ind,fname)Savesallsubimagesofspriteindasastriptothefilewiththenamefname.Thismustbea.pngfile.Only

Page 340: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

availableintheProEdition.

Page 341: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Sounds

Thefollowingfunctionswillgiveyouinformationaboutasound:

sound_exists(ind)Returnswhetherasoundwiththegivenindexexists.sound_get_name(ind)Returnsthenameofthesoundwiththegivenindex.sound_get_kind(ind)Returnsthekindofthesoundwiththegivenindex(0=normal,1=background,2=3d,3=mmplayer).sound_get_preload(ind)Returnswhetherthesoundwiththegivenindexhaspreloadset.

Soundsusemanyresourcesandmostsystemscanstoreandplayonlyalimitednumberofsounds.Ifyoumakealargegameyouwouldliketohavemorecontroloverwhichsoundsareloadedinaudiomemoryatwhattimes.Youcanusetheswitchoffthepreloadoptionforsoundstomakesuresoundsareonlyloadedwhenused.Thisthoughhastheproblemthatyoumightgetasmallhiccupwhenthesoundisusedfirst.Also,soundsarenotautomaticallyunloadedwhenyoudon'tneedthemanymore.Formorecontrolyoucanusethefollowingfunctions.

sound_discard(index)Freestheaudiomemoryusedfortheindicatedsound.sound_restore(index)Restorestheindicatedsoundinaudiomemoryforimmediateplaying.

Page 342: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Backgrounds

Thefollowingfunctionswillgiveyouinformationaboutabackground:

background_exists(ind)Returnswhetherabackgroundwiththegivenindexexists.background_get_name(ind)Returnsthenameofthebackgroundwiththegivenindex.background_get_width(ind)Returnsthewidthofthebackgroundwiththegivenindex.background_get_height(ind)Returnstheheightofthebackgroundwiththegivenindex.

Incertainsituationsyoumightwanttosavethebitmapcorrespondingthebackgroundtoafile.Forthisthefollowingfunctioncanbeused:

background_save(ind,fname)Savesthebackgroundindtothefilewiththenamefname.Thismustbea.pngfile.OnlyavailableintheProEdition.

Page 343: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Fonts

Thefollowingfunctionswillgiveyouinformationaboutafont:

font_exists(ind)Returnswhetherafontwiththegivenindexexists.font_get_name(ind)Returnsthenameofthefontwiththegivenindex.font_get_fontname(ind)Returnsthefontnameofthefontwiththegivenindex.font_get_bold(ind)Returnswhetherthefontwiththegivenindexisbold.font_get_italic(ind)Returnswhetherthefontwiththegivenindexisitalic.font_get_first(ind)Returnstheindexofthefirstcharacterinthefontwiththegivenindex.font_get_last(ind)Returnstheindexofthelastcharacterinthefontwiththegivenindex.

Page 344: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Paths

Thefollowingfunctionswillgiveyouinformationaboutapath:

path_exists(ind)Returnswhetherapathwiththegivenindexexists.path_get_name(ind)Returnsthenameofthepathwiththegivenindex.path_get_length(ind)Returnsthelengthofthepathwiththegivenindex.path_get_kind(ind)Returnsthekindofconnectionsofthepathwiththegivenindex(0=straight,1=smooth).path_get_closed(ind)Returnswhetherthepathisclosedornot.path_get_precision(ind)Returnstheprecisionusedforcreatingsmoothedpaths.path_get_number(ind)Returnsthenumberofdefiningpointsforthepath.path_get_point_x(ind,n)Returnsthex-coordinateofthen'thdefiningpointforthepath.0isthefirstpoint.path_get_point_y(ind,n)Returnsthey-coordinateofthen'thdefiningpointforthepath.0isthefirstpoint.path_get_point_speed(ind,n)Returnsthespeedfactoratthen'thdefiningpointforthepath.0isthefirstpoint.path_get_x(ind,pos)Returnsthex-coordinateatpositionposforthepath.posmustliebetween0and1.path_get_y(ind,pos)Returnsthey-coordinateatpositionposforthepath.posmustliebetween0and1.path_get_speed(ind,pos)Returnsthespeedfactoratpositionposforthepath.posmustliebetween0and1.

Page 345: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Scripts

Thefollowingfunctionswillgiveyouinformationaboutascript:

script_exists(ind)Returnswhetherascriptwiththegivenindexexists.script_get_name(ind)Returnsthenameofthescriptwiththegivenindex.script_get_text(ind)Returnsthetextstringofthescriptwiththegivenindex.

Page 346: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Timelines

Thefollowingfunctionswillgiveyouinformationaboutatimeline:

timeline_exists(ind)Returnswhetheratimelinewiththegivenindexexists.timeline_get_name(ind)Returnsthenameofthetimelinewiththegivenindex.

Page 347: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Objects

Thefollowingfunctionswillgiveyouinformationaboutanobject:

object_exists(ind)Returnswhetheranobjectwiththegivenindexexists.object_get_name(ind)Returnsthenameoftheobjectwiththegivenindex.object_get_sprite(ind)Returnstheindexofthedefaultspriteoftheobjectwiththegivenindex.object_get_solid(ind)Returnswhethertheobjectwiththegivenindexisdefaultsolid.object_get_visible(ind)Returnswhethertheobjectwiththegivenindexisdefaultvisible.object_get_depth(ind)Returnsthedepthoftheobjectwiththegivenindex.object_get_persistent(ind)Returnswhethertheobjectwiththegivenindexispersistent.object_get_mask(ind)Returnstheindexofthemaskoftheobjectwiththegivenindex(-1ifishasnospecialmask).object_get_parent(ind)Returnsindexoftheparentobjectofobjectind(anegativevalueisreturnedifithasnoparent).object_is_ancestor(ind1,ind2)Returnswhetherobjectind2isanancestorofobjectind1.

Page 348: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Rooms

Thefollowingfunctionswillgiveyouinformationaboutaroom:

room_exists(ind)Returnswhetheraroomwiththegivenindexexists.room_get_name(ind)Returnsthenameoftheroomwiththegivenindex.

Notethat,becauseroomschangeduringtheplayingofthegame,thereareotherroutinestogetinformationaboutthecontentsofthecurrentroom.

Page 349: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Changingresources

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Itispossibletocreatenewresourcesduringthegame.Alsoyoucanchangeexistingresources.Thischapterdescribesthepossibilities.Bewarnedthough.Changingresourceseasilyleadstoseriouserrorsinyourgames!!!Youmustfollowthefollowingruleswhenchangingresources:

Don'tchangeresourcesthatarebeingused.Thiswillleadtoerrors!Forexample,don'tchangeaspritethatisbeingusedbyaninstance.Whenyousavethegameduringplaying,addedandchangedresourcesareNOTstoredwiththesavegame.Soifyouloadthesavedgamelater,thesemightnotbethereanymore.Ingeneral,whenyoumanipulateresourcesyoucannolongerusethebuilt-insystemforloadingandsavinggames.Whenyourestartthegameduringplaying,thechangedresourcesareNOTrestoredtotheiroriginalshape.Ingeneral,whenyoumanipulateresourcesyoucannolongerusetheactionorfunctiontorestartthegame.Resourcemanipulationcanbeslow.Forexample,changingspritesorbackgroundsisrelativelyslow.Sodon'tuseitduringthegameplay.Creatingresourcesduringgameplay(inparticularspritesandbackground)easilyuseshugeamountofmemory.Sobeextremelycarefulwiththis.Forexample,ifyouhavea32frame128x128animatedspriteandyoudecidetocreate36rotatedcopiesofityouwilluseup36x32x128x128x4=72MBofmemory!Makesureyoudeleteresourcesyounolongerneed.Otherwisethesystemsoonrunsoutofmemory.

Ingeneral,youshouldnotchangeanyresourcesduringgameplay.Bettercreateandchangetheresourcesatthebeginningofthegameormaybeatthebeginningofaroom.

Page 350: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Informationonchangingresourcescanbefoundinthefollowingpages:

SpritesSoundsBackgroundsFontsPathsScriptsTimelinesObjectsRooms

Page 351: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Sprites

Thefollowingroutinesareavailableforchangingspriteproperties:

sprite_set_offset(ind,xoff,yoff)Setstheoffsetofthespritewiththegivenindex.

Thefollowingroutinescanbeusedtocreatenewspritesandtoremovethem.

sprite_duplicate(ind)Createsaduplicateofthespritewiththegivenindex.Itreturnstheindexofthenewsprite.Whenanerroroccurs-1isreturned.sprite_assign(ind,spr)Assignstheindicatedspritetospriteind.Sothismakesacopyofthesprite.Inthiswayyoucaneasilysetanexistingspritetoadifferent,e.g.newsprite.sprite_merge(ind1,ind2)Mergestheimagesfromspriteind2intospriteind1,addingthemattheend.Ifthesizesdon'tmatchthespritesarestretchedtofit.Spriteind2isnotdeleted!sprite_add(fname,imgnumb,removeback,smooth,xorig,yorig)Addstheimagestoredinthefilefnametothesetofspriteresources.Manydifferentimagefiletypescanbedealtwith.Whentheimageisnotagifimageitcanbeastripcontaininganumberofsubimagesforthespritenexttoeachother.Useimgnumbtoindicatetheirnumber(1forasingleimage).For(animated)gifimages,thisargumentisnotused;thenumberofimagesinthegiffileisused.removebackindicateswhethertomakeallpixelswiththebackgroundcolor(left-bottompixel)transparent.smoothindicateswhethertosmooththeedges.xorigandyorigindicatethepositionoftheorigininthesprite.Thefunctionreturnstheindexofthenewspritethatyoucanthenusetodrawitortoassignittothevariablesprite_indexofaninstance.Whenanerroroccurs-1isreturned.sprite_replace(ind,fname,imgnumb,removeback,smooth,xorig,yorig)

Sameasabovebutinthiscasethespritewithindexindisreplaced.Thefunctionreturnswhetheritissuccessful.sprite_add_sprite(fname)Addsthespritestoredthefilefnameto

Page 352: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

thesetofspriteresources.Thefilemustbea.gmsprfilethatissavedinthespritepropertyforminGameMaker.Asthisfilecontainsallspritesettings,nofurtherargumentsarerequired.Thefunctionreturnstheindexofthenewspritethatyoucanthenusetodrawitortoassignittothevariablesprite_indexofaninstance.Whenanerroroccurs-1isreturned.sprite_replace_sprite(ind,fname)Sameasabovebutinthiscasethespritewithindexindisreplaced.Thefunctionreturnswhetheritissuccessful.sprite_create_from_screen(x,y,w,h,removeback,smooth,xorig,yorig)

Createsaspritebycopyingthegivenareafromthescreen.removebackindicateswhethertomakeallpixelswiththebackgroundcolor(left-bottompixel)transparent.smoothindicateswhethertosmooththeboundaries.Thismakesitpossibletocreateanyspriteyouwant.Drawtheimageonthescreenusingthedrawingfunctionsandnextcreateaspritefromit.(Ifyoudon'tdothisinthedrawingeventyoucanevendoitinsuchawaythatitisnotvisibleonthescreenbynotrefreshingthescreen.)Theotherparametersareasabove.Thefunctionreturnstheindexofthenewsprite.Aworkofcautionisrequiredhere.Eventhoughwespeakaboutthescreen,itisactuallythedrawingregionthatmatters.Thefactthatthereisawindowonthescreenandthattheimagemightbescaledinthiswindowdoesnotmatter.sprite_add_from_screen(ind,x,y,w,h,removeback,smooth)Addsanareaofthescreenasanextsubimagetothespritewithindexind.sprite_create_from_surface(id,x,y,w,h,removeback,smooth,xorig,yorig)

Createsaspritebycopyingthegivenareafromthesurfacewiththegivenid.removebackindicateswhethertomakeallpixelswiththebackgroundcolor(left-bottompixel)transparent.smoothindicateswhethertosmooththeboundaries.Thismakesitpossibletocreateanyspriteyouwant.Drawtheimageonthesurfaceusingthedrawingfunctionsandnextcreateaspritefromit.Thefunctionreturnstheindexofthenewsprite.Notethatalphavaluesaremaintainedinthesprite.sprite_add_from_surface(ind,id,x,y,w,h,removeback,smooth)Addsanareaofthesurfaceidasanextsubimagetothespritewithindexind.

Page 353: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

sprite_delete(ind)Deletesthespritefrommemory,freeingthememoryused.

Thefollowingroutineexiststochangetheappearanceofasprite.

sprite_set_alpha_from_sprite(ind,spr)Changesthealpha(transparancy)valuesinthespritewithindexindusingtheintensityvaluesinthespritespr.Thiscannotbeundone.

Finally,youcanchangethecollisioncheckingmaskforthespritewiththefollowingroutine.Pleaserealizethatthisdoesnotworkcorrectlywhenaninstancewiththatspriteisalreadypresentintheroom.

sprite_collision_mask(ind,sepmasks,bboxmode,bbleft,bbright,bbtop,bbbottom,kind,tolerance)

Changesthecollisionmaskforthespritewithindexind.sepmasksindicateswhethertheremustbeseparatecollisionmasksforallsubimages.bboxmodeistheboundingboxmode(0=automatic,1=fullimage,2=userdefined).bbleft,bbright,bbtop,bbbottomindicatetheboundingboxincaseofuserdefinedboundingbox.Youcanuse0forallthesevaluesintheothercases.kindisthekindofmask(0=precise,1=boundingbox,2=disk,3=diamond).toleranceindicatesthetoleranceinthetransparencyvalue(0=notolerance,255=fulltolerance).

Page 354: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Sounds

Thefollowingroutinescanbeusedtocreatenewsoundsandtoremovethem.

sound_add(fname,kind,preload)Addsasoundresourcetothegame.fnameisthenameofthesoundfile.kindindicatesthekindofsound(0=normal,1=background,2=3d,3=mmplayer)preloadindicateswhetherthesoundshouldimmediatelybestoredinaudiomemory(trueorfalse).Thefunctionreturnstheindexofthenewsound,whichcanbeusedtoplaythesound.(-1ifanerroroccurred,e.g.thefiledoesnotexist).sound_replace(index,fname,kind,preload)Sameasthepreviousfunctionbutthistimeanewsoundisnotcreatedbuttheexistingsoundindexisreplaced,freeingtheoldsound.Returnswhethercorrect.sound_delete(index)Deletestheindicatedsound,freeingallmemoryassociatedwithit.Itcannolongerberestored.

Page 355: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Backgrounds

Thefollowingroutinescanbeusedtocreatenewbackgroundsandtoremovethem.

background_duplicate(ind)Createsaduplicateofthebackgroundwiththegivenindex.Itreturnstheindexofthenewbackground.Whenanerroroccurs-1isreturned.background_assign(ind,back)Assignstheindicatedbackgroundtobackgroundind.Sothismakesacopyofthebackground.background_add(fname,removeback,smooth)Addstheimagestoredinthefilefnametothesetofbackgroundresources.Manydifferenttypesofimagescanbedealtwith.Whentheimagehasanalphachannel,thisisusedfortransparency.removebackindicateswhethertomakeallpixelswiththebackgroundcolor(left-bottompixel)transparent.smoothindicateswhethertosmooththeboundaries.Thefunctionreturnstheindexofthenewbackgroundthatyoucanthenusetodrawitortoassignittothevariablebackground_index[0]tomakeitvisibleinthecurrentroom.Whenanerroroccurs-1isreturned.background_replace(ind,fname,removeback,smooth)Sameasabovebutinthiscasethebackgroundwithindexindisreplaced.Thefunctionreturnswhetheritissuccessful.Whenthebackgroundiscurrentlyvisibleintheroomitwilbereplacedalso.background_add_background(fname)Addsthebackgroundstoredthefilefnametothesetofbackgroundresources.Thefilemustbea.gmbckfilethatissavedinthebackgroundpropertyforminGameMaker.Asthisfilecontainsallbackgroundsettings,nofurtherargumentsarerequired.Thefunctionreturnstheindexofthenewbackgroundthatyoucanthenusetodrawitortoassignittothevariablebackground_index[0]tomakeitvisibleinthecurrentroom.Whenanerroroccurs-1isreturned.background_replace_background(ind,fname)Sameasabovebutinthiscasethebackgroundwithindexindisreplaced.Thefunctionreturnswhetheritissuccessful.Whenthebackgroundiscurrently

Page 356: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

visibleintheroomitwilbereplacedalso.background_create_color(w,h,col)Createsabackgroundofthegivensizeandwiththegivencolor.Itreturnstheindexofthenewbackground.Whenanerroroccurs-1isreturned.background_create_gradient(w,h,col1,col2,kind)Createsagradientfilledbackgroundofthegivensize.col1andcol2indicatethetwocolors.kindisanumberbetween0and5indicatingthekindofgradient:0=horizontal1=vertical,2=rectangle,3=ellipse,4=doublehorizontal,5=doublevertical.Itreturnstheindexofthenewbackground.Whenanerroroccurs-1isreturned.background_create_from_screen(x,y,w,h,removeback,smooth)

Createsabackgroundbycopyingthegivenareafromthescreen.removebackindicateswhethertomakeallpixelswiththebackgroundcolor(left-bottompixel)transparent.smoothindicateswhethertosmooththeboundaries.Thisfunctionmakesitpossibletocreateanybackgroundyouwant.Drawtheimageonthescreenusingthedrawingfunctionsandnextcreateabackgroundfromit.(Ifyoudon'tdothisinthedrawingeventyoucanevendoitinsuchawaythatitisnotvisibleonthescreenbynotrefreshingthescreen.)Thefunctionreturnstheindexofthenewbackground.Aworkofcautionisrequiredhere.Eventhoughwespeakaboutthescreen,itisactuallythedrawingregionthatmatters.Thefactthatthereisawindowonthescreenandthattheimagemightbescaledinthiswindowdoesnotmatter.background_create_from_surface(id,x,y,w,h,removeback,smooth)

Createsabackgroundbycopyingthegivenareafromthesurfacewiththegivenid.removebackindicateswhethertomakeallpixelswiththebackgroundcolor(left-bottompixel)transparent.smoothindicateswhethertosmooththeboundaries.Thisfunctionmakesitpossibletocreateanybackgroundyouwant.Drawtheimageonthesurfaceusingthedrawingfunctionsandnextcreateabackgroundfromit.Notethatalphavaluesaremaintainedinthebackground.background_delete(ind)Deletesthebackgroundfrommemory,freeingthememoryused.

Thefollowingroutineexiststochangetheappearanceofabackground.

background_set_alpha_from_background(ind,back)Changesthe

Page 357: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

alpha(transparancy)valuesinthebackgroundwithindexindusingtheintensityvaluesinthebackgroundback.Thiscannotbeundone.

Page 358: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Fonts

Itispossibletocreate,replace,anddeletefontsduringthegameusingthefollowingfunctions.(Don'treplaceafontthatissetasthecurrentfontoratleastsetitagainafterwards.)

font_add(name,size,bold,italic,first,last)Addsanewfontandreturnsitsindex,indicatingthename,size,whetheritisboldoritalic,andthefirstandlastcharacterthatmustbecreated.font_add_sprite(spr,first,prop,sep)Addsanewfontandreturnsitsindex.Thefontiscreatedfromasprite.Thespriteshouldcontainasubimageforeachcharacter.firstindicatetheindexofthefirstcharacterinthesprite.Forexample,useord('0')ifyourspriteonlycontainsthedigits.propindicateswhetherthefontisproportional.Inaproportionalfont,foreachcharacterthewidthoftheboundingboxisusedasthecharacterwidth.Finally,sepindicatestheamountofwhitespacethatmustseparatethecharactershorizontally.Atypicalvaluewouldliebetween2and8dependingonthefontsize.font_replace(ind,name,size,bold,italic,first,last)Replacesthefontindwithanewfont,indicatingthename,size,whetheritisboldoritalic,andthefirstandlastcharacterthatmustbecreated.font_replace_sprite(ind,spr,first,prop,sep)Replacesthefontindwithanewsprite-basedfont.font_delete(ind)Deletesthefontwiththegivenindex,freeingthememoryituses.

Page 359: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Paths

Itispossibletocreatepathsandtoaddpointstopaths.However,neverchangeapaththatisbeingusedbyaninstance.Thiscanleadtounexpectedresults.Thefollowingfunctionsexist:

path_set_kind(ind,val)Setsthekindofconnectionsofthepathwiththegivenindex(0=straight,1=smooth).path_set_closed(ind,closed)Setswhetherthepathmustbeclosed(true)oropen(false).path_set_precision(ind,prec)Setstheprecisionwithwhichthesmoothpathiscalculated(shouldliebetween1and8).path_add()Addsanewemptypaths.Theindexofthepathisreturned.path_delete(ind)Deletesthepathwiththegivenindex.path_duplicate(ind)Createsaduplicatecopyofthepathwiththegivenindex.Returnstheindexofthecopy.path_assign(ind,path)Assignstheindicatedpathtopathind.Sothismakesacopyofthepath.Inthiswayyoucaneasilysetanexistingpathtoadifferent,e.g.newpath.path_append(ind,path)Appendstheindicatedpathtopathind.path_add_point(ind,x,y,speed)Addsapointtothepathwiththegivenindex,atposition(x,y)andwiththegivenspeedfactor.Rememberthatafactorof100correspondstotheactualspeed.Lowervaluesmeanslowingdownandhighermeanspeedingup.path_insert_point(ind,n,x,y,speed)Insertsapointinthepathwiththegivenindexbeforepointn,atposition(x,y)andwiththegivenspeedfactor.path_change_point(ind,n,x,y,speed)Changesthepointninthepathwiththegivenindextoposition(x,y)andthegivenspeedfactor.path_delete_point(ind,n)Deletesthepointninthepathwiththegivenindex.path_clear_points(ind)Clearsallthepointsinthepath,turningitintoanemptypath.path_reverse(ind)Reversesthepath.

Page 360: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

path_mirror(ind)Mirrorsthepathhorizontally(withrespecttoitscenter).path_flip(ind)Flipsthepathvertically(withrespecttoitscenter).path_rotate(ind,angle)Rotatesthepathcounterclockwiseoverangledegrees(arounditscenter).path_scale(ind,xscale,yscale)Scalesthepathwiththegivenfactors(fromitscenter).path_shift(ind,xshift,yshift)Shiftsthepathoverthegivenamount.

Page 361: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Scripts

Scriptscannotbechangedduringtheexecutionofthegame.Thescriptsarepartofthegamelogic.Changingscriptswouldleadtoself-rewritingcodewhichveryeasilyleadstoerrors.Alsothereareotherwaystoachievethis.Ifyoureallyneedtoexecuteapieceofcodethatisnotknownatdesigntime(e.g.fromafile)youcanusethefollowingfunctions:

execute_string(str,arg0,arg1,...)Executethepieceofcodeinthestringstrwiththeindicatedarguments.execute_file(fname,arg0,arg1,...)Executethepieceofcodeinthefilewiththeindicatedarguments.

Sometimesyouwanttostoreascriptindexinavariableandexecuteit.Forthisyoucanusethefollowingfunction

script_execute(scr,arg0,arg1,...)Executethescriptwithindexscrwiththegivenarguments.

Page 362: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Timelines

Thefollowingroutinesareavailableforcreatingandchangingtimelines.Don'tchangetimelinesthatareinuse!

timeline_add()Addsanewtimeline.Itreturnstheindexofthetimeline.timeline_delete(ind)Deletesthetimelinewiththegivenindex.Makesurenoinstancesusesthetimelineinanyroom.timeline_clear(ind)Clearsthetimelinewiththegivenindexremovingallitsmoments.Makesurenoinstancesusesthetimelineatthemoment.timeline_moment_add(ind,step,codestr)Addsacodeactiontothetimelineatmomentstep.codestrcontainsthecodefortheactions.Ifthestepdoesnotexistitiscreated.Soyoucanaddmultiplecodeactionsforthesamemoment.timeline_moment_clear(ind,step)Youcanusethisfunctiontoclearalltheactionsforaparticularmoment.

Page 363: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Objects

Alsoobjectscanbemanipulatedandcreatedduringthegameplay.NEVERchangeordeleteanobjectforwhichthereareinstances.Thiscanleadtounexpectedeffectsascertainobjectpropertiesarestoredwiththeinstanceand,hence,changingthemintheobjectwillnothavethedesiredeffect.

object_set_sprite(ind,spr)Setsthespriteoftheobjectwiththegivenindex.Use-1toremovethecurrentspritefromtheobject.object_set_solid(ind,solid)Setswhetherinstancescreatedoftheobjectmustdefaultbesolid(trueorfalse).object_set_visible(ind,vis)Setswhetherinstancescreatedoftheobjectmustdefaultbevisible(trueorfalse).object_set_depth(ind,depth)Setsthedefaultdepthofinstancescreatedoftheobject.object_set_persistent(ind,pers)Setswhetherinstancescreatedoftheobjectmustdefaultbepersistent(trueorfalse).object_set_mask(ind,spr)Setsthespritemaskoftheobjectwiththegivenindex.Use-1tosetthemasktobethespriteoftheobject.object_set_parent(ind,obj)Setstheparentoftheobject.Use-1tonothaveaparent.Changingtheparentchangesthebehaviorofinstancesoftheobject.

Thefollowingroutinesareusefulforcreatingobjectsonthefly.Aswithallresourcechangingroutines,beverycarefulthatyoudon'tcreatenewobjectsallthetime.

object_add()Addsanewobject.Itreturnstheindexoftheobject.Youcannowusethisindexintheroutinesabovetosetcertainpropertiesoftheobjectandthenyoucanusetheindextocreateinstancesoftheobject.object_delete(ind)Deletestheobjectwiththegivenindex.Makesurenoinstancesoftheobjectexistinanyoftherooms.object_event_add(ind,evtype,evnumb,codestr)Togivetheobjectabehaviorwemustdefineeventsfortheobject.Youcanonlyadd

Page 364: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

codeactionstoevents.Youneedtospecifytheobject,theeventtype,theeventnumber(usetheconstantsthathavebeenspecifiedbeforefortheevent_perform()function).Finallyyouprovidethecodestringthatmustbeexecuted.Youcanaddmultiplecodeactionstoeachevent.object_event_clear(ind,evtype,evnumb)Youcanusethisfunctiontoclearalltheactionsforaparticularevent.

Creatingobjectsisinparticularusefulwhenyouaredesigningscriptsoractionlibraries.Forexample,aninitializationscriptcancreateanobjecttodisplayatextandanotherscriptcanaddsuchanobjectwithaparticulartext.Inthiswayyouhaveasimplemechanismtodisplaytextswithouttheneedtocreateobjectsusingthestandardinterface.

Page 365: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Rooms

Manipulatingroomsontheflyisadangerousthingtodo.Youhavetorealizethatroomschangeallthetimeduetowhatishappeninginthegame.Thisnormallyonlyinvolvesthecurrentlyactiveroomandtherearemanyroutinesdescribedinprevioussectionstomanipulatetheinstances,backgrounds,andtilesintheactiveroom.Butchangesintheactiveroomwilllastiftheroomispersistent.Hence,youshouldnevermanipulateaspectsofthecurrentlyactiveroomoranyroomthatispersistentandthathasalreadybeenvisitedbefore.Suchchangesingeneralwon'tbenoticedbutmightsometimesevenleadtounexpectederrors.Duetothefactthatroomsarelinkedinacomplicatedwaythereisalsonoroutinetodeletearoom.

Thefollowingroutinesareavailable

room_set_width(ind,w)Setsthewidthfortheroomwiththeindicatedindex.room_set_height(ind,h)Setstheheightfortheroomwiththeindicatedindex.room_set_caption(ind,str)Setsthecaptionfortheroomwiththeindicatedindex.room_set_persistent(ind,val)Setswhethertheroomwiththeindicatedindexispersistentornot.room_set_code(ind,str)Setstheinitializationcodestringfortheroomwiththeindicatedindex.room_set_background_color(ind,col,show)Setsthecolorpropertiesfortheroomwiththeindicatedindexifisdoesnothaveabackgroundimage.colindicatesthecolorandshowindicateswhetherthecolormustbeshownornot.room_set_background(ind,bind,vis,fore,back,x,y,htiled,vtiled,hspeed,vspeed,alpha)

Setsbackgroundwithindexbind(0-7)fortheroomwiththeindicatedindex.visindicateswhetherthebackgroundisvisibleandforewhetheritisactuallyaforeground.backistheindexofthebackgroundimage.x,yindicatethepositionoftheimageandhtiledandvtiledindicatewhethertheimagemustbetiled.hspeedand

Page 366: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

vspeedindicatethespeedwithwhichthebackgroundmovesandalphaindicatesanalphatranslucencyvalue(1=solidandfastest).room_set_view(ind,vind,vis,xview,yview,wview,hview,xport,yport,wport,hport,hborder,vborder,hspeed,vspeed,obj)

Setstheviewwithindexvind(0-7)fortheroomwiththeindicatedindex.visindicateswhethertheviewisvisible.xview,yview,wview,andhviewindicatethepositionoftheviewintheroom.xport,yport,wport,andhportindicatethepositiononthescreen.Whentheviewmustfollowanobjecthborderandvborderindicatetheminimalvisibleborderthatmustbekeptaroundtheobject.hspeedandvspeedindicatethemaximalspeedwithwhichtheviewcanmove.objistheindexoftheobjectortheindexoftheinstance.room_set_view_enabled(ind,val)Setswhetherviewsmustbeenabledfortheroomwiththeindicatedindex.room_add()Addsanewroom.Itreturnstheindexoftheroom.Notethattheroomwillnotbepartoftheroomorder.Sothenewroomdoesnothaveapreviousoranextroom.Ifyouwanttomovetoanaddedroomyoumustprovidetheindexoftheroom.room_duplicate(ind)Addsacopyoftheroomwiththegivenindex.Itreturnstheindexoftheroom.room_assign(ind,room)Assignstheindicatedroomtoroomind.Sothismakesacopyoftheroom.room_instance_add(ind,x,y,obj)Addsanewinstanceofobjectobjtotheroom,placingitattheindicateposition.Itreturnstheindexoftheinstance.room_instance_clear(ind)Removesallinstancesfromtheindicatedroom.room_tile_add(ind,back,left,top,width,height,x,y,depth)Addsanewtiletotheroomattheindicateposition.Itreturnstheindexofthetile.backisthebackgroundfromwhichthetileistaken.left,top,widthandheightindicatethepartofthebackgroundthatformsthetile.x,yisthepositionofthetileintheroomanddepthisthedepthofthetile.room_tile_add_ext(ind,back,left,top,width,height,x,y,depth,xscale,yscale,alpha)

Sameasthepreviousroutinebutthistimeyoucanalsospecifyascalingfactorinxandydirectionandanalphatransparencyforthetile.room_tile_clear(ind)Removesalltilesfromtheindicatedroom.

Page 367: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 368: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Files,registry,andexecutingprograms

Inmoreadvancedgamesyouprobablywanttoreaddatafromafilethatyouprovidewiththegame.Oryoumightwanttostoreinformationbetweenrunsofthegame.Andinsomesituationsyoumightneedtoexecuteexternalprograms.

Informationcanbefoundinthefollowingpages:

FilesRegistryINIFilesExecutingPrograms

Page 369: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Files

Itisusefultouseexternalfilesingames.Forexample,youcouldmakeafilethatdescribesatwhatmomentscertainthingsshouldhappen.Alsoyouprobablywanttosaveinformationforthenexttimethegameisrun(forexample,thecurrentroom).Thefollowingfunctionsexisttoreadandwritedataintextfiles:

file_text_open_read(fname)Opensthefilewiththeindicatednameforreading.Thefunctionreturnstheidofthefilethatmustbeusedintheotherfunctions.Youcanopenmultiplefilesatthesametime(32max).Don'tforgettoclosethemonceyouarefinishedwiththem.file_text_open_write(fname)Openstheindicatedfileforwriting,creatingitifitdoesnotexist.Thefunctionreturnstheidofthefilethatmustbeusedintheotherfunctions.file_text_open_append(fname)Openstheindicatedfileforappendingdataattheend,creatingitifitdoesnotexist.Thefunctionreturnstheidofthefilethatmustbeusedintheotherfunctions.file_text_close(fileid)Closesthefilewiththegivenfileid.file_text_write_string(fileid,str)Writesthestringtothefilewiththegivenfileid.file_text_write_real(fileid,x)Writetherealvaluetothefilewiththegivenfileid.(Asseparatorbetweentheintegeranddecimalpartalwaysadotisused.file_text_writeln(fileid)Writeanewlinecharactertothefile.file_text_read_string(fileid)Readsastringfromthefilewiththegivenfileidandreturnsthisstring.Astringendsattheendofline.file_text_read_real(fileid)Readsarealvaluefromthefileandreturnsthisvalue.file_text_readln(fileid)Skipstherestofthelineinthefileandstartsatthestartofthenextline.file_text_eof(fileid)Returnswhetherwereachedtheendofthefile.file_text_eoln(fileid)Returnswhetherwereachedtheendofa

Page 370: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

lineinthefile.

Tomanipulatefilesinthefilesystemyoucanusethefollowingfunctions:

file_exists(fname)Returnswhetherthefilewiththegivennameexists(true)ornot(false).file_delete(fname)Deletesthefilewiththegivenname.file_rename(oldname,newname)Renamesthefilewithnameoldnameintonewname.file_copy(fname,newname)Copiesthefilefnametothenewname.directory_exists(dname)Returnswhethertheindicateddirectorydoesexist.Thenamemustincludethefullpath,notarelativepath.directory_create(dname)Createsadirectorywiththegivenname(includingthepathtowardsit)ifitdoesnotexist.Thenamemustincludethefullpath,notarelativepath.file_find_first(mask,attr)Returnsthenameofthefirstfilethatsatisfiesthemaskandtheattributes.Ifnosuchfileexists,theemptystringisreturned.Themaskcancontainapathandcancontainwildchars,forexample'C:\temp\*.doc'.Theattributesgivetheadditionalfilesyouwanttosee.(Sothenormalfilesarealwaysreturnedwhentheysatisfythemask.)Youcanaddupthefollowingconstantstoseethetypeoffilesyouwant:

fa_readonlyread-onlyfiles

fa_hiddenhiddenfiles

fa_sysfilesystemfiles

fa_volumeidvolume-idfiles

fa_directorydirectories

fa_archivearchivedfiles

file_find_next()Returnsthenameofthenextfilethatsatisfiesthepreviouslygivenmaskandtheattributes.Ifnosuchfileexists,theemptystringisreturned.file_find_close()Mustbecalledafterhandlingallfilestofreememory.file_attributes(fname,attr)Returnswhetherthefilehasalltheattributesgiveninattr.Useacombinationoftheconstantsindicatedabove.

Page 371: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Thefollowingfunctionscanbeusedtochangefilenames.Notethatthesefunctionsdonotworkontheactualfilestheyonlydealwiththestrings.

filename_name(fname)Returnsthenamepartoftheindicatedfilename,withtheextensionbutwithoutthepath.filename_path(fname)Returnsthepathpartoftheindicatedfilename,includingthefinalbackslash.filename_dir(fname)Returnsthedirectorypartoftheindicatedfilename,whichnormallyisthesameasthepathexceptforthefinalbackslash.filename_drive(fname)Returnsthedriveinformationofthefilename.filename_ext(fname)Returnstheextensionpartoftheindicatedfilename,includingtheleadingdot.filename_change_ext(fname,newext)Returnstheindicatedfilename,withtheextension(includingthedot)changedtothenewextension.Byusinganemptystringasthenewextensionyoucanremovetheextension.

Inraresituationsyoumightneedtoreaddatafrombinaryfiles.Thefollowinglow-levelroutinesexistforthis:

file_bin_open(fname,mod)Opensthefilewiththeindicatedname.Themodeindicateswhatcanbedonewiththefile:0=reading,1=writing,2=bothreadingandwriting).Whenthefiledoesnotexistitiscreated.Thefunctionreturnstheidofthefilethatmustbeusedintheotherfunctions.Youcanopenmultiplefilesatthesametime(32max).Don'tforgettoclosethemonceyouarefinishedwiththem.file_bin_rewrite(fileid)Rewritesthefilewiththegivenfileid,thatis,clearsitandstartswritingatthestart.file_bin_close(fileid)Closesthefilewiththegivenfileid.file_bin_size(fileid)Returnsthesize(inbytes)ofthefilewiththegivenfileid.file_bin_position(fileid)Returnsthecurrentposition(inbytes;0isthefirstposition)ofthefilewiththegivenfileid.file_bin_seek(fileid,pos)Movesthecurrentpositionofthefiletotheindicatedposition.Toappendtoafilemovethepositiontothesizeofthefilebeforewriting.

Page 372: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

file_bin_write_byte(fileid,byte)Writesabyteofdatatothefilewiththegivenfileid.file_bin_read_byte(fileid)Readsabyteofdatafromthefileandreturnsthis.

Iftheplayerhascheckedsecuremodeinhispreferences,foranumberoftheseroutines,youarenotallowedtospecifyapath,andonlyfilesintheapplicationfoldercane.g.bewritten.

Ifyouincludedfilesinthegameexecutableanddidnotautomaticallyexportthematthestartofthegame,youcanusethefollowingfunctionstodothis.

export_include_file(fname)Exportstheincludedfilewiththenamefname.Thismustbeastringvariable,sodon'tforgetthequotes.export_include_file_location(fname,location)Exportstheincludedfilewiththenamefnametothegivenlocation.Locationmustcontainthepathandthefilename.discard_include_file(fname)Discardtheincludedfilewiththenamefname,freeingthememoryused.Thismustbeastringvariable,sodon'tforgetthequotes.

Thefollowingfourread-onlyvariablescanbeuseful:

game_id*Uniqueidentifierforthegame.Youcanusethisifyouneedauniquefilename.working_directory*Workingdirectoryforthegame.(Notincludingthefinalbackslash.)program_directory*Directoryinwhichthegameexecutableisstored.(Notincludingthefinalbackslash.)Whenyourunastandalonegamethisisnormallythesameastheworkingdirectoryunlessthegamee.g.opensafileusingthefileselector.Notethatwhentestingagameyouarecreatingtheprogramandworkingdirectorywillbedifferent.Inthatcasetheworkingdirectoryistheplacewheretheeditableversionisstoredwhiletheprogramdirectoryisatemporarydirectoryfortesting.temp_directory*Temporarydirectorycreatedforthegame.(Notincludingthefinalbackslash.)Youcanstoretemporaryfileshere.

Page 373: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Theywillberemovedattheendofthegame.

Incertainsituationsyoumightwanttogiveplayersthepossibilityofprovidingcommandlineargumentstothegametheyarerunning(forexampletocreatecheatsorspecialmodes).Togettheseargumentsyoucanusethefollowingtworoutines.

parameter_count()Returnsthenumberofcommand-lineparameters.Theactualparameterscanberetrievedwiththefollowingfunction.parameter_string(n)Returnscommand-lineparametersn.Thefirstparameterhasindex1.Thelastonehasindexparameter_count().Index0isaspecialone.Itisthefilenameofthegameexecutable(includingthepath).

Youcanreadthevalueofenvironmentvariablesusingthefollowingfunction:

environment_get_variable(name)Returnsthevalue(astring)oftheenvironmentvariablewiththegivenname.

Finally,ifyouareinterestedinthesizeofthediskandthefreespace,youcanusethefollowingfunctions:

disk_size(drive)Returnsthesizeoftheindicateddriveinbytes.drivemustbeacapitalletter,e.g.'C'.Ifyoudonotprovidethedrive,thedriveofthecurrentworkingdirectoryisused.disk_free(drive)Returnstheamountoffreespaceontheindicateddriveinbytes.drivemustbeacapitalletter,e.g.'C'.Ifyoudonotprovidethedrive,thedriveofthecurrentworkingdirectoryisused.

Page 374: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Registry

Ifyouwanttostoreasmallamountofinformationbetweenrunsofthegamethereisasimplermechanismthanusingafile.Youcanusetheregistry.TheregistryisalargedatabasethatWindowsmaintainstokeeptrackofallsortsofsettingsforprograms.Anentryhasaname,andavalue.Youcanusebothstringandrealvalues.Thefollowingfunctionsexist:

registry_write_string(name,str)Createsanentryintheregistrywiththegivennameandstringvalue.registry_write_real(name,x)Createsanentryintheregistrywiththegivennameandrealvalue.registry_read_string(name)Returnsthestringthatthegivennameholds.(Thenamemustexist.Otherwiseanemptystringisreturned.)registry_read_real(name)Returnstherealvaluethatthegivennameholds.(Thenamemustexist.Otherwisethenumber0isreturned.)registry_exists(name)Returnswhetherthegivennameexists.

Actually,valuesintheregistryaregroupedintokeys.Theaboveroutinesallworkonvalueswithinthekeythatisespeciallycreatedforyourgame.Yourprogramcanusethistoobtaincertaininformationaboutthesystemthegameisrunningon.Youcanalsoreadvaluesinotherkeys.Youcanwritethemalsobutbeverycareful.YOUCANEASILYDESTROYYOURSYSTEMthisway.(Writeisnotallowedinsecuremode.)Notethatkeysareagainplacedingroups.ThefollowingroutinesdefaultworkonthegroupHKEY_CURRENT_USER.Butyoucanchangetherootgroup.So,forexample,ifyouwanttofindoutthecurrenttempdir,use

path=registry_read_string_ext('\Environment','TEMP');

Thefollowingfunctionsexist:

registry_write_string_ext(key,name,str)Createsanentryinthekeyintheregistrywiththegivennameandstringvalue.

Page 375: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

registry_write_real_ext(key,name,x)Createsanentryinthekeyintheregistrywiththegivennameandrealvalue.registry_read_string_ext(key,name)Returnsthestringthatthegivennameintheindicatedkeyholds.(Thenamemustexist.Otherwiseanemptystringisreturned.)registry_read_real_ext(key,name)Returnstherealvaluethatthegivennameintheindicatedkeyholds.(Thenamemustexist.Otherwisethenumber0isreturned.)registry_exists_ext(key,name)Returnswhetherthegivennameexistsinthegivenkey.registry_set_root(root)Setstherootfortheotherroutines.Usethefollowingvalues:

0=HKEY_CURRENT_USER1=HKEY_LOCAL_MACHINE2=HKEY_CLASSES_ROOT3=HKEY_USERS

Page 376: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

INIfiles

TopasscertainparametersettingstoprogramsastandardmechanismistheuseofINIfiles.INIfilescontainsectionsandeachsectioncontainsanumberofname-valuepairs.Forexample,hereisatypicalINIfile:

[Form]

Top=100

Left=100

Caption=Thebestgameever

[Game]

MaxScore=12324

Thisfilecontainstwosections,onecallFormandtheothercalledGame.Thefirstsectioncontainsthreepairs.Thefirsttwohavearealvaluewhilethethirdhasastringvalue.SuchINIfilesareeasytocreateandchange.ThefollowingfunctionsexistinGameMakertoreadandchangethedatainthem.

ini_open(name)OpenstheINIfilewiththegivenname.Theinifilemustbestoredinthesamefolderasthegame!ini_close()ClosesthecurrentlyopenINIfile.ini_read_string(section,key,default)Readsthestringvalueoftheindicatedkeyintheindicatedsection.Whenthekeyorsectiondoesnotexistthedefaultvalueisreturned.ini_read_real(section,key,default)Readstherealvalueoftheindicatedkeyintheindicatedsection.Whenthekeyorsectiondoesnotexistthedefaultvalueisreturned.ini_write_string(section,key,value)Writesthestringvaluefortheindicatedkeyintheindicatedsection.ini_write_real(section,key,value)Writestherealvaluefortheindicatedkeyintheindicatedsection.ini_key_exists(section,key)Returnswhethertheindicatedkeyexistsintheindicatedsection.ini_section_exists(section)Returnswhethertheindicatedsectionexists.

Page 377: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ini_key_delete(section,key)Deletestheindicatedkeyfromtheindicatedsection.ini_section_delete(section)Deletestheindicatedsection.

Page 378: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Executingprograms

GameMakeralsohasthepossibilitytostartexternalprograms.Therearetwofunctionsavailableforthis:execute_programandexecute_shell.Thefunctionexecute_programstartsaprogram,possiblywithsomearguments.Itcanwaitfortheprogramtofinish(pausingthegame)orcontinuethegame.Thefunctionexecute_shellopensafile.Thiscanbeanyfileforwhichsomeassociationisdefined,e.g.anhtml-file,awordfile,etc.Oritcanbeaprogram.Itcannotwaitforcompletionsothegamewillcontinue.

execute_program(prog,arg,wait)Executesprogramprogwithargumentsarg.waitindicateswhethertowaitforfinishing.execute_shell(prog,arg)Executestheprogram(orfile)intheshell.

Bothfunctionswillnotworkiftheplayersetsthesecuremodeinthepreferences.Youcancheckthisusingtheread-onlyvariable:

secure_mode*Whetherthegameisrunninginsecuremode.

Page 379: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Datastructures

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Ingamesyouoftenneedtostoreinformation.Forexampleyouneedtostorelistsofitemsthatapersoncarriesoryouwanttostoreplacesthatstillneedtobevisited.Youcanusethearraysforthis.Butifyouwanttodomorecomplicatedoperations,likesortingthedataorsearchingforaparticularitem,youneedtowritelargepiecesofGMLcodewhichcanbeslowtoexecute.

Toremedythis,GameMakerhasanumberofbuilt-indatastructuresthatcanbeaccessedthroughfunctions.Atthemomenttherearesixdifferenttypesofdatastructureavailable:stacks,queues,lists,maps,priorityqueues,andgrids.Eachofthesedatastructuresistunedforaparticulartypeofuse(seebelow).

Alldatastructuresworkgloballyinthesameway.Youcancreateadatastructurewithafunctionthatreturnsanidforthestructures.Youusethisidtoperformoperationsonthedatastructures.Onceyouaredoneyoudestroythedatastructureagaintosavestorage.Youcanuseasmanyofthestructuresatthesamemomentasyouwant.Allstructurecanstorebothstringsandrealvalues.

Pleasenotethatdatastructuresandtheircontentarenotsavedwhenyousavethegameusingtheactionsorfunctionsforthat.Ifyouusedatastructuresandwanttoallowforsavesyouhavetocreateyourownmechanismforthat.

Whencomparingvalues,forexamplewhensearchinginamaporsortingalist,GameMakermustdecidewhentwovaluesareequal.Forstringsandintegervaluesthisisclearbutforrealnumbers,duetoround-offerrors,equalnumbercaneasilybecomeunequal.Forexample(5/3)*3willnotbeequalto5.Toavoidthis,aprecisionisused.Whenthedifferencebetweentwonumbersissmallerthanthisprecisiontheyareconsideredequal.Defaultaprecisionof0.0000001isused.Youcan

Page 380: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

changethisprecisionusingthefollowingfunction:

ds_set_precision(prec)Setstheprecisionusedforcomparisons.

ThisprecisionisusedinalldatastructuresbutnotinothercomparisonsinGML!

Informationondatastructurescanbefoundinthefollowingpages:

StacksQueuesListsMapsPriorityQueuesGrids

Page 381: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Stacks

AstackdatastructureisasocalledLIFO(Last-InFirst-Out)structures.Youcanpushvaluesonastackandtheremovethemagainbypoppingthemfromthestack.Thevaluethatwaspushedonthestackmostrecentlyisthefirsttobepoppedfromitagain.Stacksareoftenusedwhenthereareinterruptstohandle,orwhenhavingrecursivefunctions.Thefollowingfunctionsexistforstacks:

ds_stack_create()Createsanewstack.Thefunctionreturnsanintegerasanidthatmustbeusedinallotherfunctionstoaccesstheparticularstack.Youcancreatemultiplestacks.ds_stack_destroy(id)Destroysthestackwiththegivenid,freeingthememoryused.Don'tforgettocallthisfunctionwhenyouarereadywiththestructure.ds_stack_clear(id)Clearsthestackwiththegivenid,removingalldatafromitbutnotdestroyingit.ds_stack_copy(id,source)Copiesthestacksourceintothestackwiththegivenid.ds_stack_size(id)Returnsthenumberofvaluesstoredinthestack.ds_stack_empty(id)Returnswhetherthestackisempty.Thisisthesameastestingwhetherthesizeis0.ds_stack_push(id,val)Pushesthevalueonthestack.ds_stack_pop(id)Returnsthevalueonthetopofthestackandremovesitfromthestack.ds_stack_top(id)Returnsthevalueonthetopofthestackbutdoesnotremoveitfromthestack.ds_stack_write(id)Turnsthedatastructureintoastringandreturnsthisstring.Thestringcanthenbeusedtoe.g.saveittoafile.Thisprovidesaneasymechanismforsavingdatastructures.ds_stack_read(id,str)Readsthedatastructurefromthegivenstring(ascreatedbythepreviouscall).

Page 382: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics
Page 383: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Queues

AqueueissomewhatsimilartoastackbutitworksonaFIFO(First-InFirst-Out)basis.Thevaluethatisputinthequeuefirstisalsothefirsttoberemovedfromit.Itworkslikeaqueueinashop.Thepersonwhoisfirstinaqueueisservedfirst.Queuesaretypicallyusedtostorethingsthatstillneedtobedonebuttherearemanyotheruses.Thefollowingfunctionsexist(notethatthefirstfiveareequivalenttothefunctionsforstacks;alldatastructureshavethesefivefunctions):

ds_queue_create()Createsanewqueue.Thefunctionreturnsanintegerasanidthatmustbeusedinallotherfunctionstoaccesstheparticularqueue.Youcancreatemultiplequeues.ds_queue_destroy(id)Destroysthequeuewiththegivenid,freeingthememoryused.Don'tforgettocallthisfunctionwhenyouarereadywiththestructure.ds_queue_clear(id)Clearsthequeuewiththegivenid,removingalldatafromitbutnotdestroyingit.ds_queue_copy(id,source)Copiesthequeuesourceintothequeuewiththegivenid.ds_queue_size(id)Returnsthenumberofvaluesstoredinthequeue.ds_queue_empty(id)Returnswhetherthequeueisempty.Thisisthesameastestingwhetherthesizeis0.ds_queue_enqueue(id,val)Entersthevalueinthequeue.ds_queue_dequeue(id)Returnsthevaluethatislongestinthequeueandremovesitfromthequeue.ds_queue_head(id)Returnsthevalueattheheadofthequeue,thatis,thevaluethathasbeenthelongestinthequeue.(Itdoesnotremoveitfromthequeue.)ds_queue_tail(id)Returnsthevalueatthetailofthequeue,thatis,thevaluethathasmostrecentlybeenaddedtothequeue.(Itdoesnotremoveitfromthequeue.)ds_queue_write(id)Turnsthedatastructureintoastringandreturnsthisstring.Thestringcanthenbeusedtoe.g.saveittoafile.This

Page 384: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

providesaneasymechanismforsavingdatastructures.ds_queue_read(id,str)Readsthedatastructurefromthegivenstring(ascreatedbythepreviouscall).

Page 385: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Lists

Aliststoresacollectionofvaluesinaparticularorder.Youcanaddvaluesattheendorinsertthemsomewhereinthemiddleofthelist.Youcanaddressthevaluesusinganindex.Alsoyoucansorttheelements,eitherinascendingordescendingorder.Listscanbeusedinmanyways,forexampletostorechangingcollectionsofvalues.Theyareimplementedusingsimplearraysbut,asthisisdoneincompiledcodeitisalotfasterthanusinganarrayyourself.Thefollowingfunctionsareavailable:

ds_list_create()Createsanewlist.Thefunctionreturnsanintegerasanidthatmustbeusedinallotherfunctionstoaccesstheparticularlist.ds_list_destroy(id)Destroysthelistwiththegivenid,freeingthememoryused.Don'tforgettocallthisfunctionwhenyouarereadywiththestructure.ds_list_clear(id)Clearsthelistwiththegivenid,removingalldatafromitbutnotdestroyingit.ds_list_copy(id,source)Copiesthelistsourceintothelistwiththegivenid.ds_list_size(id)Returnsthenumberofvaluesstoredinthelist.ds_list_empty(id)Returnswhetherthelistisempty.Thisisthesameastestingwhetherthesizeis0.ds_list_add(id,val)Addsthevalueattheendofthelist.ds_list_insert(id,pos,val)Insertsthevalueatpositionposinthelist.Thefirstpositionis0,thelastpositionisthesizeofthelistminus1.ds_list_replace(id,pos,val)Replacesthevalueatpositionposinthelistwiththenewvalue.ds_list_delete(id,pos)Deletesthevalueatpositionposinthelist.(Position0isthefirstelement.)ds_list_find_index(id,val)Findthepositionstoringtheindicatedvalue.Ifthevalueisnotinthelist-1isreturned.ds_list_find_value(id,pos)Returnsthevaluestoredatthe

Page 386: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

indicatedpositioninthelist.ds_list_sort(id,ascend)Sortsthevaluesinthelist.Whenascendistruethevaluesaresortedinascendingorder,otherwiseindescendingorder.ds_list_shuffle(id)Shufflesthevaluesinthelistsuchthattheyendupinarandomorder.ds_list_write(id)Turnsthedatastructureintoastringandreturnsthisstring.Thestringcanthenbeusedtoe.g.saveittoafile.Thisprovidesaneasymechanismforsavingdatastructures.ds_list_read(id,str)Readsthedatastructurefromthegivenstring(ascreatedbythepreviouscall).

Page 387: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Maps

Inquiteafewsituationsyouneedtostorepairsconsistingofakeyandavalue.Forexample,acharactercanhaveanumberofdifferentitemsandforeachitemithasaparticularnumberofthose.Inthiscasetheitemisthekeyandthenumberisthevalue.Mapsmaintainsuchpairs,sortedbykey.Youcanaddpairstothemapandsearchforthevaluecorrespondingtocertainkeys.Becausethekeysaresortedyoucanalsofindpreviousandnextkeys.Sometimesitisalsousefultouseamaptojuststorekeyswithoutacorrespondingvalue.Inthatcaseyoucansimplyuseavalueof0.Thefollowingfunctionsexist:

ds_map_create()Createsanewmap.Thefunctionreturnsanintegerasanidthatmustbeusedinallotherfunctionstoaccesstheparticularmap.ds_map_destroy(id)Destroysthemapwiththegivenid,freeingthememoryused.Don'tforgettocallthisfunctionwhenyouarereadywiththestructure.ds_map_clear(id)Clearsthemapwiththegivenid,removingalldatafromitbutnotdestroyingit.ds_map_copy(id,source)Copiesthemapsourceintothemapwiththegivenid.ds_map_size(id)Returnsthenumberofkey-valuepairsstoredinthemap.ds_map_empty(id)Returnswhetherthemapisempty.Thisisthesameastestingwhetherthesizeis0.ds_map_add(id,key,val)Addsthekey-valuepairtothemap.ds_map_replace(id,key,val)Replacesthevaluecorrespondingwiththekeywithanewvalue.ds_map_delete(id,key)Deletesthekeyandthecorrespondingvaluefromthemap.(Iftherearemultipleentrieswiththesamekey,onlyoneisremoved.)ds_map_exists(id,key)Returnswhetherthekeyexistsinthemap.ds_map_find_value(id,key)Returnsthevaluecorrespondingtothekey.

Page 388: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ds_map_find_previous(id,key)Returnsthelargestkeyinthemapsmallerthantheindicatedkey.(Notethatthekeyisreturned,notthevalue.Youcanusethepreviousroutinetofindthevalue.)ds_map_find_next(id,key)Returnsthesmallestkeyinthemaplargerthantheindicatedkey.ds_map_find_first(id)Returnsthesmallestkeyinthemap.ds_map_find_last(id)Returnsthelargestkeyinthemap.ds_map_write(id)Turnsthedatastructureintoastringandreturnsthisstring.Thestringcanthenbeusedtoe.g.saveittoafile.Thisprovidesaneasymechanismforsavingdatastructures.ds_map_read(id,str)Readsthedatastructurefromthegivenstring(ascreatedbythepreviouscall).

Page 389: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Priorityqueues

Inapriorityqueueanumberofvaluesarestored,eachwithapriority.Youcanquicklyfindthevalueswithminimumandmaximumpriority.Usingthisdatastructureyoucanhandlecertainthingsintheorderofpriority.Thefollowingfunctionsexist:

ds_priority_create()Createsanewpriorityqueue.Thefunctionreturnsanintegerasanidthatmustbeusedinallotherfunctionstoaccesstheparticularpriorityqueue.ds_priority_destroy(id)Destroysthepriorityqueuewiththegivenid,freeingthememoryused.Don'tforgettocallthisfunctionwhenyouarereadywiththestructure.ds_priority_clear(id)Clearsthepriorityqueuewiththegivenid,removingalldatafromitbutnotdestroyingit.ds_priority_copy(id,source)Copiesthepriorityqueuesourceintothepriorityqueuewiththegivenid.ds_priority_size(id)Returnsthenumberofvaluesstoredinthepriorityqueue.ds_priority_empty(id)Returnswhetherthepriorityqueueisempty.Thisisthesameastestingwhetherthesizeis0.ds_priority_add(id,val,prio)Addsthevaluewiththegivenprioritytothepriorityqueue.ds_priority_change_priority(id,val,prio)Changesthepriorityofthegivenvalueinthepriorityqueue.ds_priority_find_priority(id,val)Returnsthepriorityofthegivenvalueinthepriorityqueue.ds_priority_delete_value(id,val)Deletesthegivenvalue(withitspriority)fromthepriorityqueue.ds_priority_delete_min(id)Returnsthevaluewiththesmallestpriorityanddeletesitfromthepriorityqueue.ds_priority_find_min(id)Returnsthevaluewiththesmallestprioritybutdoesnotdeleteitfromthepriorityqueue.ds_priority_delete_max(id)Returnsthevaluewiththelargestpriorityanddeletesitfromthepriorityqueue.

Page 390: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ds_priority_find_max(id)Returnsthevaluewiththelargestprioritybutdoesnotdeleteitfromthepriorityqueue.ds_priority_write(id)Turnsthedatastructureintoastringandreturnsthisstring.Thestringcanthenbeusedtoe.g.saveittoafile.Thisprovidesaneasymechanismforsavingdatastructures.ds_priority_read(id,str)Readsthedatastructurefromthegivenstring(ascreatedbythepreviouscall).

Page 391: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Grids

Agridissimplyatwo-dimensionalarray.Agridhasanintegerwidthandheight.Thestructureallowsyoutosetandretrievethevalueofcellsinthegridbygivingtheindexofit(whichstartswith0inboththex-andthey-direction).Butyoucanalsosetthevalueinregions,addvalues,andretrievethesum,max,min,andmeanvalueoveraregion.Thestructureisusefultorepresente.g.aplayingfield.Eventhoughallfunctionalitycanalsobeachievedusingtwo-dimensionalarrays,theoperationsonregionsarealotfaster.Thefollowingfunctionsexist:

ds_grid_create(w,h)Createsanewgridwiththeindicatedwidthandheight.Thefunctionreturnsanintegerasanidthatmustbeusedinallotherfunctionstoaccesstheparticulargrid.ds_grid_destroy(id)Destroysthegridwiththegivenid,freeingthememoryused.Don'tforgettocallthisfunctionwhenyouarereadywiththestructure.ds_grid_copy(id,source)Copiesthegridsourceintothegridwiththegivenid.ds_grid_resize(id,w,h)Resizesthegridtothenewwidthandheight.Existingcellskeeptheiroriginalvalue.ds_grid_width(id)Returnsthewidthofthegridwiththeindicatedid.ds_grid_height(id)Returnstheheightofthegridwiththeindicatedid.ds_grid_clear(id,val)Clearsthegridwiththegivenid,totheindicatedvalue(canbothbeanumberorastring).ds_grid_set(id,x,y,val)Setstheindicatedcellinthegridwiththegivenid,totheindicatedvalue(canbothbeanumberorastring).ds_grid_add(id,x,y,val)Addthevaluetotheindicatedcellinthegridwiththegivenid.Forstringsthiscorrespondstoconcatenation.ds_grid_multiply(id,x,y,val)Multipliesthevaluetotheindicatedcellinthegridwiththegivenid.Isonlyvalidfornumbers.ds_grid_set_region(id,x1,y1,x2,y2,val)Setstheallcellsintheregioninthegridwiththegivenid,totheindicatedvalue(canbothbeanumberorastring).

Page 392: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ds_grid_add_region(id,x1,y1,x2,y2,val)Addthevaluetothecellintheregioninthegridwiththegivenid.Forstringsthiscorrespondstoconcatenation.ds_grid_multiply_region(id,x1,y1,x2,y2,val)Multipliesthevaluetothecellsintheregioninthegridwiththegivenid.Isonlyvalidfornumbers.ds_grid_set_disk(id,xm,ym,r,val)Setsallcellsinthediskwithcenter(xm,ym)andradiusr.ds_grid_add_disk(id,xm,ym,r,val)Addthevaluetoallcellsinthediskwithcenter(xm,ym)andradiusr.ds_grid_multiply_disk(id,xm,ym,r,val)Multiplythevaluetoallcellsinthediskwithcenter(xm,ym)andradiusr.ds_grid_set_grid_region(id,source,x1,y1,x2,y2,xpos,ypos)Copiesthecontentsofthecellsintheregioningridsourcetogridid.xposandyposindicatetheplacewheretheregionmustbeplacedinthegrid.(Canalsobeusedtocopyvaluesfromoneplaceinagridtoanother.)ds_grid_add_grid_region(id,source,x1,y1,x2,y2,xpos,ypos)Addsthecontentsofthecellsintheregioningridsourcetogridid.xposandyposindicatetheplacewheretheregionmustbeaddedinthegrid.(idandsourcecanbethesame.)ds_grid_multiply_grid_region(id,source,x1,y1,x2,y2,xpos,ypos)

Multipliesthecontentsofthecellsintheregioningridsourcetogridid.xposandyposindicatetheplacewheretheregionmustbemultipliedinthegrid.(idandsourcecanbethesame.)Onlyvalidfornumbers.ds_grid_get(id,x,y)Returnsthevalueoftheindicatedcellinthegridwiththegivenid.ds_grid_get_sum(id,x1,y1,x2,y2)Returnsthesumofthevaluesofthecellsintheregioninthegridwiththegivenid.Doesonlyworkwhenthecellscontainnumbers.ds_grid_get_max(id,x1,y1,x2,y2)Returnsthemaximumofthevaluesofthecellsintheregioninthegridwiththegivenid.Doesonlyworkwhenthecellscontainnumbers.ds_grid_get_min(id,x1,y1,x2,y2)Returnstheminimumofthevaluesofthecellsintheregioninthegridwiththegivenid.Doesonlyworkwhenthecellscontainnumbers.

Page 393: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

ds_grid_get_mean(id,x1,y1,x2,y2)Returnsthemeanofthevaluesofthecellsintheregioninthegridwiththegivenid.Doesonlyworkwhenthecellscontainnumbers.ds_grid_get_disk_sum(id,xm,ym,r)Returnsthesumofthevaluesofthecellsinthedisk.ds_grid_get_disk_min(id,xm,ym,r)Returnstheminofthevaluesofthecellsinthedisk.ds_grid_get_disk_max(id,xm,ym,r)Returnsthemaxofthevaluesofthecellsinthedisk.ds_grid_get_disk_mean(id,xm,ym,r)Returnsthemeanofthevaluesofthecellsinthedisk.ds_grid_value_exists(id,x1,y1,x2,y2,val)Returnswhetherthevalueappearssomewhereintheregion.ds_grid_value_x(id,x1,y1,x2,y2,val)Returnsthex-coordinateofthecellinwhichthevalueappearsintheregion.ds_grid_value_y(id,x1,y1,x2,y2,val)Returnsthey-coordinateofthecellinwhichthevalueappearsintheregion.ds_grid_value_disk_exists(id,xm,ym,r,val)Returnswhetherthevalueappearssomewhereinthedisk.ds_grid_value_disk_x(id,xm,ym,r,val)Returnsthex-coordinateofthecellinwhichthevalueappearsinthedisk.ds_grid_value_disk_y(id,xm,ym,r,val)Returnsthey-coordinateofthecellinwhichthevalueappearsinthedisk.ds_grid_shuffle(id)Shufflesthevaluesinthegridsuchthattheyendupinarandomorder.ds_grid_write(id)Turnsthedatastructureintoastringandreturnsthisstring.Thestringcanthenbeusedtoe.g.saveittoafile.Thisprovidesaneasymechanismforsavingdatastructures.ds_grid_read(id,str)Readsthedatastructurefromthegivenstring(ascreatedbythepreviouscall).

Page 394: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Creatingparticles

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Particlesystemsaremeanttocreatespecialeffects.Particlesaresmallelements,representedbyalittlesprite.Suchparticlesmovearoundaccordingtopredefinedrulesandcanchangesize,orientation,color,etc.whiletheymove.Manysuchparticlestogethercancreatee.g.fireworks,flames,explosions,rain,snow,starfields,flyingdebris,etc.

GameMakercontainsanextensiveparticlesystemthatcanbeusedtocreategreateffects.Becauseofitsgeneralityitisnotsimpletousesobetterreadthissectioncarefullybeforetrying.

Ifthisistoocomplicatedforyou,thereisalsoaverysimplemechanismtocreatedifferenttypesofexplosions,smoke,rain,andevenfireworks.

Particlesystemshavemanyparametersanditisnotalwayseasytounderstandhowtocreatetheeffectsyouwant.Firstofallthereareparticletypes.Aparticletypedefinesaparticularkindofparticles.Suchtypeshavemanyparametersthatdescribetheshape,size,color,andmotionoftheparticles.Particletypesneedtobedefinedonlyonceandcanthenbeusedeverywhereinthegame.

Secondlythereareparticlesystems.Therecanbedifferentparticlesystemsinthegame.Aparticlesystemcanhaveparticlesofthedifferenttypes.Aparticlesystemhasemittersthatcreatetheparticles,eithercontinuouslyorinbursts.Itcanalsohaveattractorsthatattractparticles.Finally,itcanhavedestroyersthatdestroyparticles.Onceparticlesarecreatedinaparticlesystem,theyareautomaticallyhandled(updatedanddrawn)bythesystem.

Informationonparticlescanbefoundinthefollowingpages:

SimpleEffectsParticleTypesParticleSystems

Page 395: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

EmittersAttractorsDestroyersDeflectorsChangersFireworkExample

Page 396: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

SimpleEffects

Theeasiestwayofcreatingparticlesistousetheeffectsmechanism.Effectsarecreatedusingtheparticlesystembutyoudonothavetoworryaboutallthedetails.Yousimplyspecifythetypeofeffect,thepositionwhereitmustbecreated,itssize,anditscolor.Thatisall.

Thereareanumberofdifferentkindsofeffects:

ef_explosion

ef_ring

ef_ellipse

ef_firework

ef_smoke

ef_smokeup

ef_star

ef_spark

ef_flare

ef_cloud

ef_rain

ef_snow

Someyouwanttocreatejustonce(liketheexplosion)andsomeyouwanttocreateineverystep(likethesmokeortherain).Notethatrainandsnowarealwayscreatedatthetopoftheroomsothepositionisirrelevantinthiscase.

Eventhoughthismightsoundlimited,theycanactuallybeusedtocreategreateffects.Forexamplebycreatingasmalpuffofredsmokebelowamovingspaceshipineachstep,atailoffireiscreated.Thefollowingtwofunctionsexisttocreatetheeffects:

effect_create_below(kind,x,y,size,color)Createsaneffectofthegivenkind(seeabove)attheindicatedposition.sizegivethesizeasfollows:0=small,1=medium,2=large.colorindicatesthecolortobeused.Theeffectiscreatedbelowtheinstances,thatis,atadepth

Page 397: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

of100000.effect_create_above(kind,x,y,size,color)Similartothepreviousfunctionbutthistimetheeffectiscreatedontopoftheinstances,thatis,atadepthof-100000.

Ifyouwanttoremovealleffects,callthefollowingfunction:

effect_clear()Clearsalleffects.

Page 398: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Particletypes

Aparticletypedescribestheshape,color,motion,etc.ofaparticularkindofparticles.Youneedtodefineaparticletypeonlyonceinthegame.Afterthisitcanbeusedinanyparticlesysteminthegame.Particletypeshavealargenumberofparametersthatcanbeusedtochangeallaspectsofit.Settingtheserightyoucancreatealmostanyeffectyoulike.Wewilldiscussthesettingsbelow.

Anumberofroutinesareavailabletocreatenewparticletypesanddestroythemagain:

part_type_create()Createsanewparticletype.Itreturnstheindexofthetype.Thisindexmustbeusedinallcallsbelowtosetthepropertiesoftheparticletype.Soyouwilloftenstoreitinaglobalvariable.part_type_destroy(ind)Destroysparticletypeind.Callthisifyoudon'tneeditanymoretosavespace.part_type_exists(ind)Returnswhethertheindicatedparticletypeexists.part_type_clear(ind)Clearstheparticletypeindtoitsdefaultsettings.

Theshapeofaparticle

Aparticlehasashape.Thisshapeisindicatedbyasprite.Youcanuseanyspriteyoulikeforyourparticlesbutthereare15built-insprites.Theseareall64x64insizeandhavealphavaluessetsuchthattheynicelyblendwiththebackground.Theyareindicatebythefollowingconstants:

pt_shape_pixel

pt_shape_disk

pt_shape_square

pt_shape_line

Page 399: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

pt_shape_star

pt_shape_circle

pt_shape_ring

pt_shape_sphere

pt_shape_flare

pt_shape_spark

pt_shape_explosion

pt_shape_cloud

pt_shape_smoke

pt_shape_snow

Yousettheshapeusingthefollowingfunction:

part_type_shape(ind,shape)Setstheshapeoftheparticletypetoanyoftheconstantsabove(defaultispt_shape_pixel).

Youcanalsouseyourownspritefortheparticle.Ifthespritehasmultiplesubimagesyoucanindicatewhatshouldbedonewiththem.Youcanpickarandomone,animatethesprite,startatthebeginningoftheanimationoratarandomplace,etc.Youusethefollowingfunctionforthis.

part_type_sprite(ind,sprite,animat,stretch,random)Setsyourownspritefortheparticletype.Withanimateyouindicatewhetherthespriteshouldbeanimated(1)ornot(0).Withstretch(1or0)youindicatewhethertheanimationmustbestretchedoverthelifetimeoftheparticle.Andwithrandom(1or0)youcanindicatewhetherarandomsubimagemustbechoosenasstartingimage.

Onceyouhavechoosenthespritefortheparticletype(eitheradefaultshapeoryourown)youcanindicatethesizeofit.Asizeof1indicatesthenormalsizeofthesprite.Aparticletypecanbedefinedsuchthatallparticleshavethesamesizeorhavedifferentsizes.Youcanindicatearangeofsizes.Also,youcanindicatewhetherthesizeshouldchangeoverthelifetimeoftheparticleandwhethersomewigglinginthesizewillhappen,givingablinkingeffect.

part_type_size(ind,size_min,size_max,size_incr,size_wiggle)

Page 400: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Setsthesizeparametersfortheparticletype.Youspecifytheminimumstartingsize,themaximumstartingsize,thesizeincreaseineachstep(useanegativenumberforadecreaseinsize)andtheamountofwiggling.(Thedefaultsizeis1anddefaultthesizedoesnotchange.)part_type_scale(ind,xscale,yscale)Setsthehorizontalandverticalscale.Thisfactorismultipliedwiththesize.Itisinparticularusefulwhenyouneedtoscaledifferentlyinx-andy-direction.

Theparticlesalsohaveanorientation.Againtheorientationcanbethesameforallparticles,canbedifferent,andcanchangeoverthelifetimeofthesprite.Theanglesspecifycounter-clockwiserotations,indegrees.

part_type_orientation(ind,ang_min,ang_max,ang_incr,ang_wiggle,ang_relative)

Setstheorientationanglepropertiesfortheparticletype.Youspecifytheminimumangle,themaximumangle,theincreaseineachstepandtheamountofwigglinginangle.(Defaultallvaluesare0.)Youcanalsoindicatewhetherthegivenangleshouldberelative(1)tothecurrentdirectionofmotionorabsolute(0).E.g.bysettingallvaluesto0butang_relativeto1,theparticleorientationwillpreciselyfollowthepathoftheparticle.

Colorandblending

Particleswillhaveacolor.Therearedifferentwaysinwhichyoucanspecifycolorsforaparticle.Thesimplestwayistoindicateasinglecolor.Youcanalsospecifytwoorthreecolorsbetweenwhichthecoloroftheparticleisinterpolatedduringitslifetime.Forexample,theparticlecanstartwhiteandbecomemoreandmoreblackoveritslifetime.Anotherpossibilityisthatyouindicatethatthecolorofeachparticlemustbedifferent,pickedfromarangeofcolors.Youcaneithergivearangeinred,greenandblue,orarangeinhue,saturation,andvalue.

Defaultthecoloriswhite.Whenyouuseaspritewithitsowncolors,thisisnormallywhatyouwantandnocolorneedstobespecified.

part_type_color1(ind,color1)Indicatesasinglecolortobeusedfor

Page 401: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

theparticle.part_type_color2(ind,color1,color2)Specifiestwocolorsbetweenwhichthecolorisinterpolated.part_type_color3(ind,color1,color2,color3)Similarbutthistimethecolorisinterpolatedbetweenthreecolorsthatrepresentthecoloratthestart,half-way,andattheend.part_type_color_mix(ind,color1,color2)Withthisfunctionyouindicatethattheparticleshouldgetacolorthatisarandommixtureofthetwoindicatedcolors.Thiscolorwillremainfixedoverthelifetimeoftheparticle.part_type_color_rgb(ind,rmin,rmax,gmin,gmax,bmin,bmax)Canbeusedtoindicatethateachparticlemusthaveafixedcolorbutchoosenfromarange.Youspecifyarangeinthered,green,andbluecomponentofthecolor(eachbetween0and255).part_type_color_hsv(ind,hmin,hmax,smin,smax,vmin,vmax)Canbeusedtoindicatethateachparticlemusthaveafixedcolorbutchoosenfromarange.Youspecifyarangeinthehuesaturationandvaluecomponentofthecolor(eachbetween0and255).

Besidesthecoloryoucanalsogiveanalphatransparencyvalue.Thebuilt-inparticleshapesalreadyhavesomealphatransparencybutyoucanusethesesettingstoe.g.maketheparticlevanishoveritslifetime.

part_type_alpha1(ind,alpha1)Setsasinglealphatransparencyparameter(0-1)fortheparticletype.part_type_alpha2(ind,alpha1,alpha2)Similarbutthistimeastartandendvaluearegivenandthealphavalueisinterpolatedbetweenthem.part_type_alpha3(ind,alpha1,alpha2,alpha3)Thistimethreevaluesaregivenbetweenwhichthealphatransparencyisinterpolated.

Normallyparticlesareblendedwiththebackgroundinthesamewayassprites.Butitisalsopossibletouseadditiveblending.Thisgivesinparticularagreateffectforexplosion.

part_type_blend(ind,additive)Setswhethertouseadditiveblending(1)ornormalblending(0)fortheparticletype.

Page 402: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Lifeanddeath

Particlesliveforalimitedamountoftime,theirlifetime.Afterthistheydisappear.Lifetimeismeasuredinsteps.Youcanindicatethelifetime(orarangeoflifetimes)foreachparticletype.Particlescancreatenewparticlesofdifferenttypes.Therearetwowaysforthis.Theycancreatenewparticlesineachsteportheycancreateparticleswhentheydie.Becarefulthatthetotalnumberofparticlesdoesnotgettoohigh.

part_type_life(ind,life_min,life_max)Setsthelifetimeboundsfortheparticletype.(Defaultbothare100.)part_type_step(ind,step_number,step_type)Setsthenumberandtypeofparticlesthatmustbegeneratedineachstepfortheindicatedparticletype.Ifyouuseanegativevalue,ineachstepaparticleisgeneratedwithachance-1/number.Soforexamplewithavalueof-5aparticleisgeneratedonaverageonceevery5steps.part_type_death(ind,death_number,death_type)Setsthenumberandtypeofparticlesthatmustbegeneratedwhenaparticleoftheindicatedtypedies.Againyoucanusenegativenumberstocreateaparticlewithaparticularchance.Notethattheseparticlesareonlycreatedwhentheparticlediesattheendofitslife,notwhenitdiesbecauseofadestroyer(seebelow).

Particlemotion

Particlescanmoveduringtheirlifetime.Theycangetaninitialspeed(orrangeofspeeds)anddirection,andthespeedanddirectioncanchangeovertime.Alsogravitycanbedefinedthatpullstheparticlesinaparticulardirection.Thefollowingfunctionsexistforthis:

part_type_speed(ind,speed_min,speed_max,speed_incr,speed_wiggle)

Setsthespeedpropertiesfortheparticletype.(Defaultallvaluesare0.)Youspecifyaminimalandmaximalspeed.Arandomvaluebetweenthegivenboundsischosenwhentheparticleiscreated.YoucanindicateaspeedincreaseineachstepUseanegativenumbertoslowtheparticledown(thespeedwillneverbecome

Page 403: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

smallerthan0).Finallyyoucanindicatesomeamountofwigglingofthespeed.part_type_direction(ind,dir_min,dir_max,dir_incr,dir_wiggle)

Setsthedirectionpropertiesfortheparticletype.(Defaultallvaluesare0.)Againyouspecifyarangeofdirections(incounterclockwisedegrees;0indicatedamotiontotheright).Forexample,tolettheparticlemoveinarandomdirectionchoose0and360asvalues.Youcanspecifyanincreaseindirectionforeachstep,andanamountofwiggling.part_type_gravity(ind,grav_amount,grav_dir)Setsthegravitypropertiesfortheparticletype.(Defaultthereisnogravity.)Youspecifytheamountofgravitytobeaddedineachstepandthedirection.E.g.use270foradownwardsdirection.

Page 404: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Particlesystems

Particlesliveinparticlesystems.Sotohaveparticlesinyourgameyouneedtocreateoneormoreparticlesystems.Therecanbedifferentparticlesystems(butpreferablykeeptheirnumbersmall).Forexample,ifyourgamehasanumberofballsandeachballshouldhaveatailofparticles,mostlikelyeachballhasitsownparticlesystem.Theeasiestwaytodealwithparticlesystemsistocreateoneandthencreateparticlesinit,usingtheparticletypesyouspecifiedbefore.But,aswewillseebelow,particlesystemscancontainemittersthatautomaticallyproduceparticles,attractorsthatattractthem,anddestroyersthatdestroythem.

Onceparticlesareaddedtoaparticlesystemtheyareautomaticallyupdatedeachstepanddrawn.Nofurtheractionisrequired.Tomakeitpossiblethatparticlesaredrawn,behind,infrontof,orbetweenobjectinstances,eachparticlesystemhasadepth,similartoinstancesandtiles.

Particlesystemswillliveonforeveraftertheyarecreated.Soevenifyouchangeroomorrestartthegame,thesystemsandtheparticlesremain.Soyoubettermakesureyoudestroythemonceyounolongerneedthem.

Thefollowingbasicfunctionsdealwithparticlesystems:

part_system_create()Createsanewparticlesystem.Itreturnstheindexofthesystem.Thisindexmustbeusedinallcallsbelowtosetthepropertiesoftheparticlesystem.part_system_destroy(ind)Destroystheparticlesystemind.Callthisifyoudon'tneeditanymoretosavespace.part_system_exists(ind)Returnswhethertheindicatedparticlesystemexists.part_system_clear(ind)Clearstheparticlesystemindtoitsdefaultsettings,removingallparticlesandemitterandattractorsinit.part_system_draw_order(ind,oldtonew)Setstheorderinwhichthe

Page 405: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

particlesystemdrawstheparticles.Whenoldtonewistruetheoldestparticlesaredrawnfirstandtheneweronelieontopofthem(default).Otherwisethenewestparticlesaredrawnfirst.Thiscangiveratherdifferenteffects.part_system_depth(ind,depth)Setsthedepthoftheparticlesystem.Thiscanbeusedtolettheparticlesappearbehind,infrontof,orinbetweeninstances.part_system_position(ind,x,y)Setsthepositionwheretheparticlesystemisdrawn.Thisisnormallynotnecessarybutifyouwanttohaveparticlesatapositionrelativetoamovingobject,youcansetthepositione.g.tothatobject.

Asindicatedabove,theparticlesystemisautomaticallyupdatedanddrawn.Butsometimesthisisnotwhatyouwant.Tofacilitatethis,youcanswitchoffautomaticupdatingordrawingandthendecideyourselfwhentoupdateordrawtheparticlesystem.Forthisyoucanusethefollowingfunctions:

part_system_automatic_update(ind,automatic)Indicateswhethertheparticlesystemmustbeupdatedautomatically(1)ornot(0).Defaultis1.part_system_automatic_draw(ind,automatic)Indicateswhethertheparticlesystemmustbedrawnautomatically(1)ornot(0).Defaultis1.part_system_update(ind)Thisfunctionsupdatesthepositionofallparticlesinthesystemandletstheemitterscreateparticles.Youonlyhavetocallthiswhenupdatingisnotautomatic.(Althoughsometimesitisalsousefultocallthisfunctionacoupleoftimetogetthesystemgoing.)part_system_drawit(ind)Thisfunctionsdrawstheparticlesinthesystem.Youonlyhavetocallthiswhendrawingisnotautomatic.Itshouldbecalledinthedraweventofsomeobject.

Thefollowingfunctionsdealwithparticlesinaparticlesystems:

part_particles_create(ind,x,y,parttype,number)Thisfunctionscreatesnumberparticlesoftheindicatedtypeatpostion(x,y)inthesystem.

Page 406: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

part_particles_create_color(ind,x,y,parttype,color,number)Thisfunctionscreatesnumberparticlesoftheindicatedtypeatpostion(x,y)inthesystemwiththeindicatedcolor.Thisisonlyusefulwhentheparticletypedefinesasinglecolor(ordoesnotdefineacoloratall).part_particles_clear(ind)Thisfunctionsremovesallparticlesinthesystem.part_particles_count(ind)Thisfunctionsreturnsthenumberofparticlesinthesystem.

Page 407: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Emitters

Emitterscreateparticles.Theycaneithercreateacontinuousstreamofparticlesorcanburstoutanumberofparticleswhenusingtheappropriatefunction.Aparticlesystemcanhaveanarbitrarynumberofemitters.Anemitterhasthefollowingproperties:

xmin,xmax,ymin,ymaxindicatetheextendoftheregioninwhichtheparticlesaregenerated.shapeindicatestheshapeoftheregion.Itcanhavethefollowingvalues:

ps_shape_rectangle

ps_shape_ellipse

ps_shape_diamond

ps_shape_line

distributionindicatesthedistributionusedtogeneratetheparticles.Itcanhavethefollowingvalues:

ps_distr_linearindicatesalineardistribution,thatiseverywhereintheregionthechanceisequalps_distr_gaussianindicatesaGaussiandistributioninwhichmoreparticlesaregeneratedinthecenterthanatthesidesoftheregionps_distr_invgaussianindicatesaninverseGaussiandistributioninwhichmoreparticlesaregeneratedatthesidesoftheregionthaninthecenter

particletypeindicatesthetypeofparticlesbeinggeneratednumberindicatesthenumberofparticlesgeneratedineachstep.Ifsmallerthan0,ineachstepaparticleisgeneratedwithachance-1/number.Soforexamplewithavalueof-5aparticleisgeneratedonaverageonceevery5steps.

Thefollowingfunctionsareavailabletosettheemittersandtoletthemcreateparticles.Notethateachofthemgetstheindexoftheparticlesystemtowhichitbelongsasafirstargument.

part_emitter_create(ps)Createsanewemitterinthegivenparticle

Page 408: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

system.Itreturnstheindexoftheemitter.Thisindexmustbeusedinallcallsbelowtosetthepropertiesoftheemitter.part_emitter_destroy(ps,ind)Destroysemitterindintheparticlesystem.Callthisifyoudon'tneeditanymoretosavespace.part_emitter_destroy_all(ps)Destroysallemittersintheparticlesystemthathavebeencreated.part_emitter_exists(ps,ind)Returnswhethertheindicatedemitterexistsintheparticlesystem.part_emitter_clear(ps,ind)Clearstheemitterindtoitsdefaultsettings.part_emitter_region(ps,ind,xmin,xmax,ymin,ymax,shape,distribution)

Setstheregionanddistributionfortheemitter.part_emitter_burst(ps,ind,parttype,number)Burstsoncenumberparticlesoftheindicatedtypefromtheemitter.part_emitter_stream(ps,ind,parttype,number)Fromthismomentoncreatenumberparticlesoftheindicatedtypefromtheemitterineverystep.Ifyouindicateanumbersmallerthan0ineachstepaparticleisgeneratedwithachanceof-1/number.Soforexamplewithavalueof-5aparticleisgeneratedonaverageonceevery5steps.

Page 409: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Attractors

Besidesemittersaparticlesystemcanalsocontainattractors.Anattractorattractstheparticles(orpushesthemaway).Aparticlesystemcanhavemultipleattractors.Youarethoughrecommendedtousefewofthesebecausetheywillslowdowntheprocessingoftheparticles.Anattractorhasthefollowingproperties:

x,yindicatethepositionoftheattractor.forceindicatestheattractingforceoftheattractor.Howtheforceactsontheparticlesdependsonthefollowingparameters.distindicatesthemaximaldistanceatwhichtheattractorhaseffect.Onlyparticlescloserthatthisdistancetotheattractorwillbeattracted.kindindicatesthekindofattractor.Thefollowingvaluesexist

ps_force_constantindicatesthattheforceisconstantindependentofthedistance.ps_force_linearindicatesalinearlygrowingforce.Atthemaximaldistancetheforceis0whileatthepositionoftheattractoritattainsthegivenvalue.ps_force_quadraticindicatesthattheforcegrowsquadratic.

additiveindicateswhethertheforceisaddedtothespeedanddirectionineachstep(true)oronlyappliedtothepositionoftheparticle(false).Whenadditivetheparticlewillacceleratetowardstheattractorwhilewithanon-additiveforceitwillmovetherewithconstantspeed.

Thefollowingfunctionsexisttodefineattractors.Notethateachofthemgetstheindexoftheparticlesystemtowhichitbelongsasafirstargument.

part_attractor_create(ps)Createsanewattractorinthegivenparticlesystem.Itreturnstheindexoftheattractor.Thisindexmustbeusedinallcallsbelowtosetthepropertiesoftheattractor.part_attractor_destroy(ps,ind)Destroysattractorindintheparticlesystem.Callthisifyoudon'tneeditanymoretosavespace.

Page 410: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

part_attractor_destroy_all(ps)Destroysallattractorsintheparticlesystemthathavebeencreated.part_attractor_exists(ps,ind)Returnswhethertheindicatedattractorexistsintheparticlesystem.part_attractor_clear(ps,ind)Clearstheattractorindtoitsdefaultsettings.part_attractor_position(ps,ind,x,y)Setsthepositionofattractorindto(x,y).part_attractor_force(ps,ind,force,dist,kind,aditive)Setstheforceparametersofattractorind.

Page 411: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Destroyers

Destroyersdestroyparticleswhentheyappearintheirregion.Aparticlesystemcanhaveanarbitrarynumberofdestroyers.Adestroyerhasthefollowingproperties:

xmin,xmax,ymin,ymaxindicatestheextentoftheregioninwhichtheparticlesaredestroyed.shapeindicatestheshapeoftheregion.Itcanhavethefollowingvalues:

ps_shape_rectangle

ps_shape_ellipse

ps_shape_diamond

Thefollowingfunctionsareavailabletosetthepropertiesofthedestroyers.Notethateachofthemgetstheindexoftheparticlesystemtowhichitbelongsasafirstargument.

part_destroyer_create(ps)Createsanewdestroyerinthegivenparticlesystem.Itreturnstheindexofthedestroyer.Thisindexmustbeusedinallcallsbelowtosetthepropertiesofthedestroyer.part_destroyer_destroy(ps,ind)Destroysdestroyerindintheparticlesystem.Callthisifyoudon'tneeditanymoretosavespace.part_destroyer_destroy_all(ps)Destroysalldestroyersintheparticlesystemthathavebeencreated.part_destroyer_exists(ps,ind)Returnswhethertheindicateddestroyerexistsintheparticlesystem.part_destroyer_clear(ps,ind)Clearsthedestroyerindtoitsdefaultsettings.part_destroyer_region(ps,ind,xmin,xmax,ymin,ymax,shape)Setstheregionforthedestroyer.

Page 412: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Deflectors

Deflectorsdeflectparticleswhentheyappearintheirregion.Notethatonlythepositionoftheparticleistakenintoaccountnotitsspriteorsize.Aparticlesystemcanhaveanarbitrarynumberofdeflectors.Adeflectorhasthefollowingproperties:

xmin,xmax,ymin,ymaxindicatestheextentoftheregioninwhichtheparticlesaredeflected.kindindicatesthekindofdeflector.Itcanhavethefollowingvalues:

ps_deflect_horizontaldeflectstheparticlehorizontally;typicallyusedforverticalwallsps_deflect_verticaldeflectstheparticlevertically;typicallyusedforhorizontalwalls

frictiontheamountoffrictionasaresultoftheimpactwiththedeflector.Thehigherthisamountthemoretheparticleissloweddownonimpact.

Thefollowingfunctionsareavailabletosetthepropertiesofthedeflector.Notethateachofthemgetstheindexoftheparticlesystemtowhichitbelongsasafirstargument.

part_deflector_create(ps)Createsanewdeflectorinthegivenparticlesystem.Itreturnstheindexofthedeflector.Thisindexmustbeusedinallcallsbelowtosetthepropertiesofthedeflector.part_deflector_destroy(ps,ind)Destroysdeflectorindintheparticlesystem.Callthisifyoudon'tneeditanymoretosavespace.part_deflector_destroy_all(ps)Destroysalldeflectorsintheparticlesystemthathavebeencreated.part_deflector_exists(ps,ind)Returnswhethertheindicateddeflectorexistsintheparticlesystem.part_deflector_clear(ps,ind)Clearsthedeflectorindtoitsdefaultsettings.part_deflector_region(ps,ind,xmin,xmax,ymin,ymax)Setstheregionforthedeflector.part_deflector_kind(ps,ind,kind)Setsthekindforthedeflector.

Page 413: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

part_deflector_friction(ps,ind,friction)Setsthefrictionforthedeflector.

Page 414: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Changers

Changerschangecertainparticleswhentheyappearintheirregion.Aparticlesystemcanhaveanarbitrarynumberofchangers.Achangerhasthefollowingproperties:

xmin,xmax,ymin,ymaxindicatestheextentoftheregioninwhichtheparticlesarechanged.shapeindicatestheshapeoftheregion.Itcanhavethefollowingvalues:

ps_shape_rectangle

ps_shape_ellipse

ps_shape_diamond

parttype1indicatestheparticletypethatischanged.parttype2indicatestheparticletypeintowhichitischanged.kindindicatesthekindofchanger.Itcanhavethefollowingvalues:

ps_change_motiononlychangesthemotionparametersoftheparticle,notthecolorandshapeorlifetimesettings.ps_change_shapeonlychangestheshapeparameterslikesizeandcolorandshape.ps_change_allchangesallparameters,thisbasicallymeansthattheparticleisdestroyedandanewoneofthenewtypeiscreated.

Thefollowingfunctionsareavailabletosetthepropertiesofthechanger.Notethateachofthemgetstheindexoftheparticlesystemtowhichitbelongsasafirstargument.

part_changer_create(ps)Createsanewchangerinthegivenparticlesystem.Itreturnstheindexofthechanger.Thisindexmustbeusedinallcallsbelowtosetthepropertiesofthechanger.part_changer_destroy(ps,ind)Destroyschangerindintheparticlesystem.Callthisifyoudon'tneeditanymoretosavespace.part_changer_destroy_all(ps)Destroysallchangersintheparticlesystemthathavebeencreated.part_changer_exists(ps,ind)Returnswhethertheindicatedchanger

Page 415: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

existsintheparticlesystem.part_changer_clear(ps,ind)Clearsthechangerindtoitsdefaultsettings.part_changer_region(ps,ind,xmin,xmax,ymin,ymax,shape)Setstheregionforthechanger.part_changer_types(ps,ind,parttype1,parttype2)Setswhichparticletypethechangermustchangeintowhatothertype.part_changer_kind(ps,ind,kind)Setsthekindforthechanger.

Page 416: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

FireworkExample

Hereisanexampleofaparticlesystemthatcreatesfireworks.Thefireworkusestwoparticletypes:onethatformstherocketandonethatformstheactualfireworks.Therocketgeneratesthefireworkparticleswhenitdies.Wealsogenerateoneemitterintheparticlesystemthatregularlystreamoutrocketparticlesalongthebottomofthescreen.Tomakethisworkyouneedanobject.Initscreationeventweplacethefollowingcodethatcreatestheparticletypes,particlesystem,andtheemitter:

{

//maketheparticlesystem

ps=part_system_create();

//thefireworkparticles

pt1=part_type_create();

part_type_shape(pt1,pt_shape_flare);

part_type_size(pt1,0.1,0.2,0,0);

part_type_speed(pt1,0.5,4,0,0);

part_type_direction(pt1,0,360,0,0);

part_type_color1(pt1,c_red);

part_type_alpha2(pt1,1,0.4);

part_type_life(pt1,20,30);

part_type_gravity(pt1,0.2,270);

//therocket

pt2=part_type_create();

part_type_shape(pt2,pt_shape_sphere);

part_type_size(pt2,0.2,0.2,0,0);

part_type_speed(pt2,10,14,0,0);

part_type_direction(pt2,80,100,0,0);

part_type_color2(pt2,c_white,c_gray);

part_type_life(pt2,30,60);

part_type_gravity(pt2,0.2,270);

part_type_death(pt2,150,pt1);//createthefireworkondeath

//createtheemitter

em=part_emitter_create(ps);

part_emitter_region(ps,em,100,540,480,490,ps_shape_rectangle,ps_distr_linear);

part_emitter_stream(ps,em,pt2,-4);//createoneeveryfoursteps

Page 417: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

}

Thatwilldothetrick.Youmightwanttomakesuretheparticlesystem(andmaybeparticletypes)aredestroyedwhenmovingtoanotherroom,otherwisethefireworkwillcontinueforever.

Page 418: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Multiplayergames

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Playinggamesagainstthecomputerisfun.Butplayinggamesagainstotherhumanplayerscanbeevenmorefun.Itisalsorelativelyeasytomakesuchgamesbecauseyoudon'thavetoimplementcomplicatedcomputeropponentAI.Youcanofcoursesitwithtwoplayersbehindthesamemonitorandusedifferentkeysorotherinputdevices,butitisalotmoreinterestingwheneachplayercansitbehindhisowncomputer.Orevenbetter,oneplayersitsontheothersideoftheocean.GameMakerhasmultiplayersupport.Pleaserealizethatcreatingeffectivemultiplayergamesthatsynchronizewellandhavenolatencyisadifficulttask.Thischaptergivesabriefdescriptionofthepossibilities.Onthewebsiteatutorialisavailablewithmoreinformation.

Informationonmultiplayergamescanbefoundinthefollowingpages:

SettingupaConnectionCreatingandJoiningSessionsPlayersSharedDataMessages

Page 419: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Settingupaconnection

Fortwocomputertocommunicatetheywillneedsomeconnectionprotocol.Likemostgames,GameMakeroffersfourdifferenttypesofconnections:IPX,TCP/IP,Modem,andSerial.TheIPXconnection(tobemoreprecise,itisaprotocol)isalmostcompletelytransparent.Itcanbeusedtoplaygameswithotherpeopleonthesamelocalareanetwork.Itneedstobeinstalledonyourcomputertobeused.(Ifitdoesnotwork,consultthedocumentationofWindows.OrgototheNetworkiteminthecontrolpanelofWindowsandaddtheIPXprotocol.)TCP/IPistheinternetprotocol.Itcanbeusedtoplaywithotherplayersanywhereontheinternet,assumingyouknowtheirIPaddress.Onalocalnetworkyoucanuseitwithoutprovidingaddresses.Amodemconnectionismadethroughthemodem.Youhavetoprovidesomemodemsettings(aninitializationstringandaphonenumber)touseit.Finally,whenusingaserialline(adirectconnectionbetweenthecomputers)youneedtoprovideanumberofportsettings.TherearefourGMLfunctionsthatcanbeusedforinitializingtheseconnections:

mplay_init_ipx()initializesanIPXconnection.mplay_init_tcpip(addr)initializesaTCP/IPconnection.addrisastringcontainingthewebaddressorIPaddress,e.g.'www.gameplay.com'or'123.123.123.12',possiblyfollowedbyaportnumber(e.g.':12').Onlywhenjoiningasession(seebelow)doyouneedtoprovideanaddress.Onalocalareanetworknoaddressesarenecessary.mplay_init_modem(initstr,phonenr)initializesamodemconnection.initstristheinitializationstringforthemodem(canbeempty).phonenrisastringthatcontainsthephonenumbertoring(e.g.'0201234567').Onlywhenjoiningasession(seebelow)doyouneedtoprovideaphonenumber.mplay_init_serial(portno,baudrate,stopbits,parity,flow)

initializesaserialconnection.portnoistheportnumber(1-4).baudrateisthebaudratetobeused(100-256K).stopbitsindicatesthenumberofstopbits(0=1bit,1=1.5bit,2=2bits).parity

Page 420: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

indicatestheparity(0=none,1=odd,2=even,3=mark).Andflowindicatesthetypeofflowcontrol(0=none,1=xon/xoff,2=rts,3=dtr,4=rtsanddtr).Returnswhethersuccessful.Atypicalcallismplay_init_serial(1,57600,0,0,4).Give0asafirstargumenttoopenadialogfortheusertochangethesettings.

Yourgameshouldcalloneofthesefunctionsexactlyonce.Allfunctionsreportwhethertheyweresuccessful.Theyarenotsuccessfuliftheparticularprotocolisnotinstalledorsupportedbyyourmachine.Tocheckwhetherthereisasuccessfulconnectionavailableyoucanusethefollowingfunction

mplay_connect_status()returnsthestatusofthecurrentconnection.0=noconnection,1=IPXconnection,2=TCP/IPconnection,3=modemconnection,and4=serialconnection.

Toendtheconnectioncall

mplay_end()endsthecurrentconnection.

WhenusingaTCP/IPconnectionyoumightwanttotellthepersonyouwanttoplaythegamewithwhattheipaddressofyourcomputeris.Thefollowingfunctionhelpsyouhere:

mplay_ipaddress()returnstheIPaddressofyourmachine(e.g.'123.123.123.12')asastring.Youcane.g.displaythissomewhereonthescreen.Notethatthisroutineisslowsodon'tcallitallthetime.

Page 421: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Creatingandjoiningsessions

Whenyouconnecttoanetwork,therecanbemultiplegameshappeningonthesamenetwork.Wecallthesesessions.Thesedifferentsessionscancorrespondtodifferentgamesortothesamegame.Agamemustuniquelyidentifyitselfonthenetwork.Fortunately,GameMakerdoesthisforyou.Theonlythingyouhavetoknowisthatwhenyouchangethegameidintheoptionsformthisidentificationchanges.Inthiswayyoucanavoidthatpeoplewitholdversionsofyourgamewillplayagainstpeoplewithnewversions.

Ifyouwanttostartanewmultiplayergameyouneedtocreateanewsession.Forthisyoucanusethefollowingroutine:

mplay_session_create(sesname,playnumb,playername)createsanewsessiononthecurrentconnection.sesnameisastringindicatingthenameofthesession.playnumbisanumberthatindicatesthemaximalnumberofplayersallowedinthisgame(use0foranarbitrarynumber).playnameisyournameasplayer.Returnswhethersuccessful.

Oneinstanceofthegamemustcreatethesession.Theotherinstance(s)ofthegameshouldjointhissession.Thisisslightlymorecomplicated.Youfirstneedtolookatwhatsessionsareavailableandthenchoosetheonetojoin.Therearethreeimportantroutinesforthis:

mplay_session_find()searchesforallsessionsthatstillacceptplayersandreturnsthenumberofsessionsfound.mplay_session_name(numb)returnsthenameofsessionnumbernumb(0isthefirstsession).Thisroutinecanonlybecalledaftercallingthepreviousroutine.mplay_session_join(numb,playername)makesyoujoinsessionnumbernumb(0isthefirstsession).playernameisyournameasaplayer.Returnswhethersuccessful.

Thereisonemoreroutinethatcanchangethesessionmode.Itshould

Page 422: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

becalledbeforecreatingasession:

mplay_session_mode(move)setswhetherornottomovethesessionhosttoanothercomputerwhenthehostends.moveshouldeitherbetrueorfalse(thedefault).

Tocheckthestatusofthecurrentsessionyoucanusethefollowingfunction

mplay_session_status()returnsthestatusofthecurrentsession.0=nosession,1=createdsession,2=joinedsession.

Aplayercanstopasessionusingthefollowingroutine:

mplay_session_end()endsthesessionforthisplayer.

Page 423: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Players

Eachinstanceofthegamethatjoinsasessionisaplayer.Asindicatedabove,playershavenames.Therearethreeroutinesthatdealwithplayers.

mplay_player_find()searchesforallplayersinthecurrentsessionandreturnsthenumberofplayersfound.mplay_player_name(numb)returnsthenameofplayernumbernumb(0isthefirstplayer,whichisalwaysyourself).Thisroutinecanonlybecalledaftercallingthepreviousroutine.mplay_player_id(numb)returnstheuniqueidofplayernumbernumb(0isthefirstplayer,whichisalwaysyourself).Thisroutinecanonlybecalledaftercallingthefirstroutine.Thisidisusedinsendingandreceivingmessagestoandfromindividualplayers.

Page 424: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Shareddata

Shareddatacommunicationisprobablytheeasiestwaytosynchronizethegame.Allcommunicationisshieldedfromyou.Thereisasetof1000000valuesthatarecommontoallentitiesofthegame(preferablyonlyusethefirstfewtosavememory).Eachentitycansetvaluesandreadvalues.GameMakermakessurethateachentityseesthesamevalues.Avaluecaneitherbearealorastring.Therearejusttworoutines:

mplay_data_write(ind,val)writevalueval(stringorreal)intolocationind(indbetween0and1000000).mplay_data_read(ind)returnsthevalueinlocationind(indbetween0and1000000).Initiallyallvaluesare0.

Tosynchronizethedataonthedifferentmachinesyoucaneitheruseaguaranteedmodethatmakessurethatthechangearrivesontheothermachine(butwhichisslow)ornon-guaranteed.Tochangethisusethefollowingroutine:

mplay_data_mode(guar)setswhetherornottouseguaranteedtransmissionforshareddata.guarshouldeitherbetrue(thedefault)orfalse.

Page 425: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Messages

ThesecondcommunicationmechanismthatGameMakersupportsisthesendingandreceivingofmessages.Aplayercansendmessagestooneorallotherplayers.Playerscanseewhethermessageshavearrivedandtakeactionaccordingly.Messagescanbesentinaguaranteedmodeinwhichyouaresuretheyarrive(butthiscanbeslow)orinanon-guaranteedmode,whichisfaster.

Thefollowingmessagingroutinesexist:

mplay_message_send(player,id,val)sendsamessagetotheindicatedplayer(eitheranidentifieroraname;use0tosendthemessagetoallplayers).idisanintegermessageidentifierandvalisthevalue(eitherarealorastring).Themessageissentinnon-guaranteedmode.Ifvalcontainsastringthemaximalstringlengthallowedis30000characters.mplay_message_send_guaranteed(player,id,val)sendsamessagetotheindicatedplayer(eitheranidentifieroraname;use0tosendthemessagetoallplayers).idisanintegermessageidentifierandvalisthevalue(eitherarealorastring).Thisisaguaranteedsend.Ifvalcontainsastringthemaximalstringlengthallowedis30000characters.mplay_message_receive(player)receivesthenextmessagefromthemessagequeuethatcamefromtheindicatedplayer(eitheranidentifieroraname).Use0formessagesfromanyplayer.Theroutinereturnswhethertherewasindeedanewmessage.Ifsoyoucanusethefollowingroutinestogetitscontents:mplay_message_id()Returnstheidentifierofthelastreceivedmessage.mplay_message_value()Returnsthevalueofthelastreceivedmessage.mplay_message_player()Returnstheplayerwhosentthelastreceivedmessage.mplay_message_name()Returnsthenameoftheplayerwhosentthe

Page 426: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

lastreceivedmessage.mplay_message_count(player)Returnsthenumberofmessagesleftinthequeuefromtheplayer(use0tocountallmessage).mplay_message_clear(player)Removesallmessagesleftinthequeuefromtheplayer(use0toremoveallmessage).

Afewremarksarepertinenthere.Firstofall,ifyouwanttosendamessagetoaparticularplayeronly,youwillneedtoknowtheplayer'suniqueid.Asindicatedearlieryoucanobtainthiswiththefunctionmplay_player_id().Thisplayeridentifierisalsousedwhenreceivingmessagesfromaparticularplayer.Alternatively,youcangivethenameoftheplayerasastring.Ifmultipleplayershavethesamename,onlythefirstwillgetthemessage.

Secondly,youmightwonderwhyeachmessagehasanintegeridentifier.Thereasonisthatthishelpsyourapplicationtosenddifferenttypesofmessages.Thereceivercancheckthetypeofmessageusingtheidandtakeappropriateactions.(Becausemessagesarenotguaranteedtoarrive,sendingidandvalueindifferentmessageswouldcauseseriousproblems.)

Page 427: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

UsingDLL's

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

Pleasenotethatsinceversion7thereisanewextensionmechanisminGameMaker.Youarestronglyencouragedtousethatextensionmechanism,ratherthanthefunctionsdescribedinthissection.Seehttp://www.yoyogames.com/extensionsfordetails.Thesefunctionsaremainlyleftinforcompatibilitywiththepast.

InthosecaseswerethefunctionalityofGMLisnotenoughforyourwishes,youcanactuallyextendthepossibilitiesbyusingplug-ins.Aplug-incomesintheformofaDLLfile(aDynamicLinkLibrary).InsuchaDLLfileyoucandefinefunctions.SuchfunctionscanbeprogrammedinanyprogramminglanguagethatsupportsthecreationofDLL's(e.g.Delphi,C,C++,etc.)Youwillthoughneedtohavesomeprogrammingskilltodothis.Plug-infunctionsmusthaveaspecificformat.Theycanhavebetween0and16arguments,eachofwhichcaneitherbearealnumber(doubleinC)oranull-terminatedstring.(Formorethan4arguments,onlyrealargumentsaresupportedatthemoment.)Theymustreturneitherarealoranull-terminatedstring.

InDelphiyoucreateaDLLbyfirstchoosingNewfromtheFilemenuandthenchoosingDLL.HereisanexampleofaDLLyoucanusewithGameMakerwritteninDelphi.(NotethatthisisDelphicode,notGMLcode!)

libraryMyDLL;

usesSysUtils,Classes;

functionMyMin(x,y:double):double;cdecl;

begin

ifx<ythenResult:=xelseResult:=y;

end;

varres:array[0..1024]ofchar;

functionDoubleString(str:PChar):PChar;cdecl;

Page 428: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

begin

StrCopy(res,str);

StrCat(res,str);

Result:=res;

end;

exportsMyMin,DoubleString;

begin

end.

ThisDLLdefinestwofunctions:MyMinthattakestworealargumentsandreturnstheminimumofthetwo,andDoubleStringthatdoublesthestring.Notethatyouhavetobecarefulwithmemorymanagement.ThatiswhyIdeclaredtheresultingstringglobal.Alsonoticetheuseofthecdeclcallingconvention.Youcaneitherusecdeclorstdcallcallingconventions.OnceyoubuildtheDLLinDelphiyouwillgetafileMyDLL.DLL.Thisfilemustbeplacedintherunningdirectoryofyourgame.(OranyotherplacewhereWindowscanfindit.)

TousethisDLLinGameMakeryoufirstneedtospecifytheexternalfunctionsyouwanttouseandwhattypeofargumentstheytake.ForthisthereisthefollowingfunctioninGML:

external_define(dll,name,calltype,restype,argnumb,arg1type,arg2type,

...)Definesanexternalfunction.dllisthenameofthedllfile.nameisthenameofthefunctions.calltypeisthecallingconventionused.Forthisuseeitherdll_cdeclordll_stdcall.restypeisthetypeoftheresult.Forthisuseeitherty_realorty_string.argnumbisthenumberofarguments(0-16).Next,foreachargumentyoumustspecifyitstype.Forthisagainuseeitherty_realorty_string.Whentherearemorethan4argumentsallofthemmustbeoftypety_real.

Thisfunctionreturnstheidoftheexternalfunctionthatmustbeusedforcallingit.Sointheaboveexample,atthestartofthegameyouwouldusethefollowingGMLcode:

{

global.mmm=external_define('MyDLL.DLL','MyMin',dll_cdecl,

ty_real,2,ty_real,ty_real);

Page 429: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

global.ddd=external_define('MyDLL.DLL','DoubleString',dll_cdecl,

ty_string,1,ty_string);

}

Nowwheneveryouneedtocallthefunctions,youusethefollowingfunction:

external_call(id,arg1,arg2,...)Callstheexternalfunctionwiththegivenid,andthegivenarguments.Youneedtoprovidethecorrectnumberofargumentsofthecorrecttype(realorstring).Thefunctionreturnstheresultoftheexternalfunction.

So,forexample,youwouldwrite:

{

aaa=external_call(global.mmm,x,y);

sss=external_call(global.ddd,'Hello');

}

Ifyoudon'tneedtousetheDLLanymoreyouhadbetterfreeit.

external_free(dll)FreestheDLLwiththegivenname.ThisisinparticularnecessaryifthegameshouldremovetheDLL.AslongastheDLLisnotfreeditcannotberemoved.Bestdothise.g.inanendofgameevent.

YoumightwonderhowtomakeafunctioninaDLLthatdoessomethinginthegame.Forexample,youmightwanttocreateaDLLthataddsinstancesofobjectstoyourgame.TheeasiestwayistoletyourDLLfunctionreturnastringthatcontainsapieceofGMLcode.ThisstringthatcontainsthepieceofGMLcanbeexecutedusingtheGMLfunction

execute_string(str,arg0,arg1,...)Executethepieceofcodeinthestringstrwiththeindicatedarguments.

AlternativelyyoucanlettheDLLcreateafilewithascriptthatcanbeexecuted(thisfunctioncanalsobeusedtolatermodifythebehaviorofagame).

Page 430: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

execute_file(fname)Executethepieceofcodeinthefile.

Nowyoucancallanexternalfunctionandthenexecutetheresultingstring,e.g.asfollows:

{

ccc=external_call(global.ddd,x,y);

execute_string(ccc);

}

InsomerarecasesyourDLLmightneedtoknowthehandleofthemaingraphicswindowforthegame.ThiscanbeobtainedwiththefollowingfunctionandcanthenbepassedtotheDLL:

window_handle()Returnsthewindowhandleforthemainwindow.

NotethatDLLscannotbeusedinsecuremode.

UsingexternalDLLsisanextremelypowerfulmechanism.Butpleaseonlyuseitifyouknowwhatyouaredoing.

Page 431: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

3DGraphics

ThisfunctionalityisonlyavailableintheProEditionofGameMaker.

GameMakerisaprogrammeantformaking2-dimensionalandisometricgames.Stillthereissomefunctionalitytocreate3-dimensionalgraphics.Beforeyoustartwiththisthoughthereareafewthingsyoumustunderstand.

The3DfunctionalityinGameMakerislimitedtothegraphicspart.Thereisnosupportforother3Dfunctionality.Onceyoustartusing3DgraphicsyoumightgetproblemswithotheraspectsofGameMaker,liketheviews,depthordering,etc.Thefunctionalityislimitedandhaslowprioritytobeextended.Sodon'texpectsupportfor3Dobjectmodels,etc.Whenyouusethe3Dfunctionality,thereareanumberofotherthingsthatcannolongerbeused.

Youcannotusebackgroundandforegroundsinyourroomsanymore.(Thereasonisthattheyaretiledtofilltheimagebutwithperspectiveprojectionsthisnolongerworkcorrectly).Youcannotusethemousepositionanymore.Themousewillnotbetransformedtothe3Dcoordinates.Youcanstillgetthepositionofthemouseonthescreen(intheview)butyouwillhavetodocalculationwiththisyourself(ornotusethemouseatall).Youcannotusetilesanymore.Tileswillmostlikelynolongermatchupcorrectly.Collisioncheckingstillusesthe2-dpositionsoftheinstancesintheroom.Sothereisnocollisiondetectionin3D.Sometimesyoucanstillusethis(ifyouusetheroomasarepresentationofaflatworld(e.g.forracingorFPSgames)butinothersituationsyouhavetodothingsyourself.

All3Dfunctionalityisthroughcode.YoumustberatherfluentwiththeGMLlanguage.AlsoyoumustreallyunderstandalotabouthowGameMakerworksotherwiseyouwillrunintotrouble.

Page 432: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Youmusthavesomebasicknowledgeabout3Dgraphics.InparticularIwillusetermslikeperspectiveprojections,hiddensurfaceremoval,lighting,andfog,withoutmuchexplanation.Thereisno3DmodellinginGameMaker.AlsoIdonotplanonaddingsupportforloading3Dmodels.Youmustworkcarefullytokeepareasonablespeed.Also,thingsarenotreallyoptimizedforspeed.

Ifthisdidnotdiscourageyou,readon.

Informationon3dgraphicscanbefoundinthefollowingpages:

Goingto3DmodeEasydrawingDrawingpolygonsin3DDrawingbasicshapesViewingtheworldTransformationsFogLightingCreatingmodelsFinalwords

Page 433: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Goingto3Dmode

Ifyouwanttouse3DmodeyoufirstneedtosetGameMakerin3Dmode.Youcanlaterswitchbackto2Dmodeifyouwant.Thefollowingtwofunctionsexistforthis.

d3d_start()Startusing3Dmode.Returnswhethersuccessful.d3d_end()Stopusing3Dmode.Returnswhethersuccessful.

Notethatallfunctionsrelatedto3Dmodestartwithd3d_.

Starting3Dmodewillresultinthefollowingchanges.Firstofallhiddensurfaceremovalisswitchedon(usinga16-bitz-buffer).Thismeansthatforeachpixelonthescreenonlythedrawingwiththesmallestz-value(=depthvalue)isdrawn.Ifinstanceshavethesamedepthitisunclearwhatwillhappenandyoucangetuglyeffects.Makesureinstancesthatmightoverlapdonothavethesamedepthvalue!

Secondly,thenormalorthographicprojectionisreplacedbyaperspectiveone.Thismeansthefollowing.Normallythesizeofinstancesonthescreenisindependentonitsdepth.Withaperspectiveprojectioninstancesthathaveagreaterdepthwillappearsmaller.Whenthedepthis0itisequaltotheoldsize(unlessyouchangetheprojection;seebelow).Theviewpointforthecameraisplacedatadistanceabovetheroom.(Thisdistanceisequaltothewidthoftheroom;thatgivesareasonabledefaultprojection.)Onlyinstancesinfrontofthecameraaredrawn.Sodon'tuseinstanceswithadepthsmallerthan0(oratleastnotsmallerthan-wwherewisthewidthoftheroomortheview).

Thirdly,theverticaly-coordinateisreversed.Whilenormallythe(0,0)positionisatthetop-leftoftheview,in3Dmodethe(0,0)positionisatthebottom-leftposition,asisnormalfor3-dimensionalviews.

Youcanactuallyswitchhiddensurfaceremoveandperspectiveprojectiononoroffusingthefollowingfunctions.

Page 434: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

d3d_set_hidden(enable)Enableshiddensurfaceremoval(true)ordisablesit(false).d3d_set_perspective(enable)Enablestheuseofaperspectiveprojection(true)ordisablesit(false).

Page 435: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Easydrawing

Once3DmodehasbeenswitchedonyoucanuseGameMakerasyouareusedtoit(exceptfortheremarksmadeatthebeginning).Onlyobjectswillappearindifferentsizesbasedontheirdepthsetting.Youcanevenuseviews.Oneadditionalfunctioncanbeuseful.Ifyoudrawanumberofthingsinapieceofcodeyoumightwanttochangethedepthvaluebetweentheprimitivesyoudraw.Forthisyouuse:

d3d_set_depth(depth)Setsthedepthusedfordrawing.

Notethatatthemomentanewinstanceisdrawnthedepthisagainsettothedepthofthatinstance.

Page 436: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Drawingpolygonsin3D

Theproblemwithdrawingintheoldwayisthataspriteorpolygonalwaysliesinthexy-plane,thatis,allcornershavethesamedepth.Fortrue3Dyouwanttobeabletohaveverticesatdifferentdepths.Fromthismomentonwewilltalkaboutz-coordinateratherthandepth.Sowewanttospecifycoordinatesas(x,y,z)tuples.Forthistherearespecialversionoftheadvanceddrawingfunctions:

d3d_primitive_begin(kind)Starta3Dprimitiveoftheindicatedkind:pr_pointlist,pr_linelist,

pr_linestrip,pr_trianglelist,pr_trianglestriporpr_trianglefan.d3d_vertex(x,y,z)Addvertex(x,y,z)totheprimitive,usingthecolorandalphavaluesetbefore.d3d_vertex_color(x,y,z,col,alpha)Addvertex(x,y,z)totheprimitive,withitsowncolorandalphavalue.Thisallowsyoutocreateprimitiveswithsmoothlychangingcolorandalphavalues.d3d_primitive_end()Endthedescriptionoftheprimitive.Thisfunctionactuallydrawsit.

Forexample,todrawatetrahedron(threesidedpyramid)standingonthez=0planewithitstopatz=200,youcanusethefollowingcode:

{

d3d_primitive_begin(pr_trianglelist);

d3d_vertex(100,100,0);

d3d_vertex(100,200,0);

d3d_vertex(150,150,200);

d3d_vertex(100,200,0);

d3d_vertex(200,200,0);

d3d_vertex(150,150,200);

d3d_vertex(200,200,0);

d3d_vertex(100,100,0);

d3d_vertex(150,150,200);

d3d_vertex(100,100,0);

d3d_vertex(100,200,0);

d3d_vertex(200,200,0);

d3d_primitive_end();

}

Page 437: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Nowifyouwouldusethis,mostlikelyyouwouldjustseeatriangleonthescreenbecausethetopofthetetrahedronwillbebehinditfromtheviewpoint.Also,usingjustonecolor,itwouldbedifficulttoseethedifferentfaces.Belowwewillseewaystochangetheviewpoint.Assigningcolorscanbedoneasbeforebyaddeddraw_set_color(col)functioncallsbetweenthevertices.

Youcanalsousetexturedpoygonsin3D.Itworksexactlythesameasdescribedintheadvanceddrawingfunctionsinthedocumentation.Butthistimeyouneed3Dvariantsofthebasicfunctions.Onethingyoumustrealize.Inatexturetheposition(0,0)isthetop-leftcorner.Butoften,whenusingprojections(asindicatedbelow),thebottom-leftcorneris(0,0).Insuchacaseyoumightneedtoflipthetexturevertically.

d3d_primitive_begin_texture(kind,texid)Starta3Dprimitiveoftheindicatedkindwiththegiventexture.d3d_vertex_texture(x,y,z,xtex,ytex)Addvertex(x,y,z)totheprimitivewithposition(xtex,ytex)inthetexture,blendingwiththecolorandalphavaluesetbefore.d3d_vertex_texture_color(x,y,z,xtex,ytex,col,alpha)Addvertex(x,y,z)totheprimitivewithposition(xtex,ytex)inthetexture,blendingwithitsowncolorandalphavalue.d3d_primitive_end()Endthedescriptionoftheprimitive.Thisfunctionactuallydrawsit.

So,forexampleyoucanusethefollowingcodetodrawabackgroundimagethatdisappearsintothedistance

{

varttt;

ttt=background_get_texture(back);

d3d_primitive_begin_texture(pr_trianglefan,ttt);

d3d_vertex_texture(0,480,0,0,0);

d3d_vertex_texture(640,480,0,1,0);

d3d_vertex_texture(640,480,1000,1,1);

d3d_vertex_texture(0,480,1000,0,1);

d3d_primitive_end();

}

Page 438: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Atrianglehasafrontandabackside.Thefrontsideisdefinedtobethesidewheretheverticesaredefinedincounter-clockwiseorder.Normallybothsidesaredrawn.Butifyoumakeaclosedshapethisisawastebecausethebacksideofthetrianglecanneverbeseen.Inthiscaseyoucanswitchonbackfaceculling.Thissavesabouthalftheamountofdrawingtimebutitleavesyouwiththetaskofdefiningyourpolygonsintherightway.Thefollowingfunctionexists:

d3d_set_culling(cull)Indicatestostartbackfaceculling(true)orstopbackfaceculling(false).

Page 439: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Drawingbasicshapes

Anumberoffunctionsexistfordrawingbasicshapes,likeblocksandwalls.Notethattheseshapesalsoworkcorrectlywithbackfacecullingon.

d3d_draw_block(x1,y1,z1,x2,y2,z2,texid,hrepeat,vrepeat)Drawsablockinthecurrentcolorwiththeindicatedoppositecornersusingtheindicatedtexture.Use-1tonotuseatexture.hrepeatindicateshowoftenthetexturemustberepeatedalongthehorizontaledgeofeachface.vrepeatdoesthesamefortheverticaledge.d3d_draw_cylinder(x1,y1,z1,x2,y2,z2,texid,hrepeat,vrepeat,closed,steps)

Drawsaverticalcylinderinthecurrentcolorintheindicatedboundingboxusingtheindicatedtexture.Use-1tonotuseatexture.hrepeatindicateshowoftenthetexturemustberepeatedalongthehorizontaledgeofeachface.vrepeatdoesthesamefortheverticaledge.closedindicateswhethertoclosethetopandbottomofthecylinder.stepsindicateshowmanyrotationalstepsmustbetaken.Atypicalvalueis24.d3d_draw_cone(x1,y1,z1,x2,y2,z2,texid,hrepeat,vrepeat,closed,steps)

Drawsaverticalconeinthecurrentcolorintheindicatedboundingboxusingtheindicatedtexture.Use-1tonotuseatexture.hrepeatindicateshowoftenthetexturemustberepeatedalongthehorizontaledgeofeachface.vrepeatdoesthesamefortheverticaledge.closedindicateswhethertoclosethetopandbottomofthecylinder.stepsindicateshowmanyrotationalstepsmustbetaken.Atypicalvalueis24.d3d_draw_ellipsoid(x1,y1,z1,x2,y2,z2,texid,hrepeat,vrepeat,steps)

Drawsanellipsoidinthecurrentcolorintheindicatedboundingboxusingtheindicatedtexture.Use-1tonotuseatexture.hrepeatindicateshowoftenthetexturemustberepeatedalongthehorizontaledgeofeachface.vrepeatdoesthesamefortheverticaledge.stepsindicateshowmanyrotationalstepsmustbetaken.Atypicalvalueis24.d3d_draw_wall(x1,y1,z1,x2,y2,z2,texid,hrepeat,vrepeat)Drawsaverticalwallinthecurrentcolorwiththegivencornersusingthe

Page 440: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

indicatedtexture.Use-1tonotuseatexture.hrepeatindicateshowoftenthetexturemustberepeatedalongthehorizontaledgeofeachface.vrepeatdoesthesamefortheverticaledge.d3d_draw_floor(x1,y1,z1,x2,y2,z2,texid,hrepeat,vrepeat)Drawsa(slanted)floorinthecurrentcolorwiththegivencornersusingtheindicatedtexture.Use-1tonotuseatexture.hrepeatindicateshowoftenthetexturemustberepeatedalongthehorizontaledgeofeachface.vrepeatdoesthesamefortheverticaledge.

Thefollowingpieceofcodedrawstwoblocks:

{

varttt;

ttt=background_get_texture(back);

d3d_draw_block(20,20,20,80,40,200,ttt,1,1);

d3d_draw_block(200,300,-10,240,340,100,ttt,1,1);

}

Page 441: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Viewingtheworld

Defaultyoulookalongthenegativez-axistowardthemiddleoftheroom.Oftenin3Dgamesyouwanttochangehowyoulookattheworld.Forexample,inafirstpersonshooteryouprobablywanttohavethecameralookfromapositionabitabovethexy-planealongthexy-plane.Ingraphicstermsyouaresettingthecorrectprojection.Tochangethewayyoulookthefollowingtwofunctionsexist.

d3d_set_projection(xfrom,yfrom,zfrom,xto,yto,zto,xup,yup,zup)

Defineshowtolookintheworld.Youspecifythepointtolookfrom,thepointtolooktoandtheupvector.

Thisfunctionrequiressomeexplanation.Tosettheprojectionyoufirstneedthepositionyoulookfrom.Thisisindicatedbytheparameters(xfrom,yfrom,zfrom).Nextyoumustspecifythedirectionyoulookin.Thisisdonebygivingasecondpointtolooktowards.Thisisthepoint(xto,yto,zto).Finally,youcanstillrotatethecameraaroundthelinefromtheviewpointtothelookingpoint.Tospecifythiswemustgiveanupvector,thatis,thedirectionthatisupwardsinthecamera.Thisisgivenbythelastthreeparameters(xup,yup,zup).Letmegivenanexample.Tolookalongthexy-planeasinafirstpersonshooteryoucanuse

{

d3d_set_projection(100,100,10,200,100,10,0,0,1);

}

Soyoulookfrompoint(100,100)and10abovetheplaneinthedirectionof(200,100).Theupvectorpointsisthez-directionasrequired.Tomakethisslightlymorecomplicated,assumeyouhaveaninstanceinyourroomthatspecifiesthepositionofthecamera.Itwillhaveacurrent(x,y)positionandadirection(andmaybeevenaspeed).Youcannowspecifythisasyourcamerabyusingthefollowingcode:

{

with(obj_camera)

d3d_set_projection(x,y,10,

Page 442: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

x+cos(direction*pi/180),y-sin(direction*pi/180),10,

0,0,1);

}

Thismightlookabitcomplicated.Welookfromthecameraposition(x,y),10abovetheground.Todetermineapointinthecorrectdirectionweneedtodoalittlearithmetic.Thispointisindicatedbythenextthreeparameters.Finallyweusetheupvectorasabove.

Oneimportantremark!WhenGameMakerstartsdrawingaroomitwillsettheviewpointbacktothedefaultposition.Sothefirstthingyoumustdowhendrawingthesceneissetistotheprojectionyouwant.Thismustbedoneinadrawingevent!

Thereisalsoanextendedversionofthefunctionabove:

d3d_set_projection_ext(xfrom,yfrom,zfrom,xto,yto,zto,xup,yup,zup,angle,aspect,znear,zfar)

Anextendedversionofthisfunctioninwhichyoualsospecifytheangledefiningthefieldofview,theaspectratiobetweenhorizontalandverticalsizeoftheview,andthenearandfarclippingplanes.

Theadditionalparametersworkasfollows.Ifyouspecifiedthecameraposition,pointtolookat,andupvector,youcanstillchangehowwidethelensofthecamerais.Thisiscalledthefieldofview.Areasonablevalueissomewherebetween40and45degrees.Butyoucanchangethisifyoulike.Nextyoucanspecifytheaspectratiobetweenthehorizontalandverticalprojection.Normallyyouwanttousethesameastheaspectrationoftheroomorview,e.g.640/480.Finallyyoucanindicatetheclippingplanes.Objectsthatarecloserthanzneartothecameraarenotdrawn.Similarforobjectsfurtherthanzfar.Itcanbeimportanttosettheseparameterstoreasonablevaluesbecausetheyalsoinfluencetheprecisionofthez-comparisons.Ifyoumaketherangetoolargetheprecisiongetsworse.Defaultweuse1and32000.znearmustbelargerthan0!

Sometimesyoutemporarilyneedanormalorthographicprojectionasisusedwhenthereisno3D.Oryouwanttoreturntothedefaultperspectiveprojection.Forthisyoucanusethefollowingfunctions:

Page 443: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

d3d_set_projection_ortho(x,y,w,h,angle)Setsanormalorthographicprojectionoftheindicatedareaintheroom,rotatedovertheindicatedangle.d3d_set_projection_perspective(x,y,w,h,angle)Setsanormalperspectiveprojectionoftheindicatedareaintheroom,rotatedovertheindicatedangle.

Astandarduseforthisistodrawanoverlaytoe.g.showthescoreorotheraspects.Todosowesetanorthographicprojection.Wealsomusttemporarilyswitchoffhiddensurfaceremovalcausewewanttheinformationtobedrawnregardlessofthecurrentdepthvalue.Thefollowingexampleshowshowtocreateanoverlaywiththescore.

{

draw_set_color(c_black);

d3d_set_projection_ortho(0,0,room_width,room_height,0);

d3d_set_hidden(false);

draw_text(10,10,'Score:'+string(score));

d3d_set_hidden(true);

}

Page 444: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Transformations

Transformationallowyoutochangetheplacewherethingsaredrawnintheworld.Forexample,thefunctiontodrawblockscanonlydrawaxis-parallelblocks.Byfirstsettingarotationtransformationyoucancreaterotatedblocks.Alsospritesarealwaysdrawnparalleltothexy-plane.Bysettingatransformationyoucanchangethis.Therearetwotypesoffunctions:functionsthatsetthetransformationandfunctionsthataddtransformations.

d3d_transform_set_identity()Setsthetransformationtotheidentity(notransformation).d3d_transform_set_translation(xt,yt,zt)Setsthetransformationtoatranslationovertheindicatedvector.d3d_transform_set_scaling(xs,ys,zs)Setsthetransformationtoascalingwiththeindicatedamounts.d3d_transform_set_rotation_x(angle)Setsthetransformationtoarotationaroundthex-axiswiththeindicatedamount.d3d_transform_set_rotation_y(angle)Setsthetransformationtoarotationaroundthey-axiswiththeindicatedamount.d3d_transform_set_rotation_z(angle)Setsthetransformationtoarotationaroundthez-axiswiththeindicatedamount.d3d_transform_set_rotation_axis(xa,ya,za,angle)Setsthetransformationtoarotationaroundtheaxisindicatedbythevectorwiththeindicatedamount.d3d_transform_add_translation(xt,yt,zt)Addsatranslationovertheindicatedvector.d3d_transform_add_scaling(xs,ys,zs)Addsascalingwiththeindicatedamounts.d3d_transform_add_rotation_x(angle)Addsarotationaroundthex-axiswiththeindicatedamount.d3d_transform_add_rotation_y(angle)Addsarotationaroundthey-axiswiththeindicatedamount.d3d_transform_add_rotation_z(angle)Addsarotationaroundthez-axiswiththeindicatedamount.

Page 445: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

d3d_transform_add_rotation_axis(xa,ya,za,angle)Addsarotationaroundtheaxisindicatedbythevectorwiththeindicatedamount.

Realizethatrotationandscalingarewithrespecttotheoriginoftheworld,notwithrespecttotheobjectthatistobedrawn.Iftheobjectisnotattheoriginitwillalsomovetoadifferentplace,whichisnotwhatwewant.Sotoe.g.rotateanobjectoveritsownx-axis,wemustfirsttranslateittotheorigin,nextrotateit,andfinallytranslateitbacktoitsposition.Thisiswhatthefunctionstoaddtransformationsarefor.

Thefollowingexamplesmightexplainthisbetter.Assumewehaveaspritesprthatwewanttodrawatposition(100,100,10).Wecanusethefollowingcodetodothis

{

d3d_transform_set_translation(100,100,10);

draw_sprite(spr,0,0,0);

d3d_transform_set_identity();

}

Notethatbecauseweuseatranslationweshouldnowdrawthespriteatposition(0,0).(Thisassumesthecurrentinstancehasadepthof0!Ifyouarenotsure,firstsetthedepth.)Ifwewouldusethisinourfirstpersonshooterwewouldnotseethesprite.Thereasonisthatitisstillparalleltothexy-plane.Wewanttorotateitover90degreesalongthex-axis(ory-axis).Soweneedtoaddarotation.Remembertheorder:wemustfirstrotatethespriteandthentranslateit.Sowecanusethefollowingcode.

{

d3d_transform_set_identity();

d3d_transform_add_rotation_x(90);

d3d_transform_add_translation(100,100,10);

draw_sprite(spr,0,0,0);

d3d_transform_set_identity();

}

Sometimesyoutemporarilywanttosavethecurrenttransformation,forexampletoaddanadditionaltransformationandthenrestoretheoldone(thisoftenhappenswhendrawinghierarchicalmodels).Tothisendyoucanpushthecurrenttransformationonastackandlaterpopitfromthe

Page 446: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

stacktomakeitthecurrenttransformationagain.Thefollowingfunctionsexistforthis:

d3d_transform_stack_clear()Clearsthestackoftransformations.d3d_transform_stack_empty()Returnswhetherthetransformationstackisempty.d3d_transform_stack_push()Pushesthecurrenttransformationonthestack.Returnswhethertherewasroomonthestacktopushitthere(ifyouforgetpoppingtransformationyouatsomemomentwillrunoutofroomonthestack).d3d_transform_stack_pop()Popsthetoptransformationfromthestackandmakesitthecurrentone.Returnswhethertherewasatransformationonthestack.d3d_transform_stack_top()Makesthetoptransformationthecurrentone,butdoesnotremoveitfromthestack.Returnswhethertherewasatransformationonthestack.d3d_transform_stack_discard()Removesthetoptransformationfromthestackbutdoesnotmakeitthecurrentone.Returnswhethertherewasatransformationonthestack.

Usingtransformationisapowerfulmechanism.Butbecarefulandalwayssetthetransformationbacktotheidentityonceyouaredone.

Page 447: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Fog

Fogcanbeusedin3Dgamestomakeobjectsinthedistancelookblurredorevendisappear.Thishelpsincreatingatmosphereanditmakesitpossibletonotdrawobjectsthatarefaraway.Toenableordisablefogusethefollowingfunction:

d3d_set_fog(enable,color,start,end)Enablesordisablestheuseoffog.colorindicatesthefogcolor.startindicatesthedistanceatwhichfogmuststart.endindicatesthedistanceatwhichfogismaximalandnothingcanbeseenanymore.

Tobetterunderstandwhatishappening,thereareactuallytwotypesoffog,tablebasedfogandvertexbasedfog.Thefirsttypecalculatesfogvaluesonapixelbasis.Thesecondtypecalculatesthefogvalueforeachvertexandtheninterpolatesthese.Thefirsttypeisbetterbutnotalwayssupported.GameMakertriestousetablebasedfogwhensupportedandotherwiseusesvertexbasedfog(unlessnofogissupported).Notethatcertaingraphicscardindicatethattheycanhandletablebasedfogbutoffertheuserthepossibilitytoswitchthisoffintheadvanceddisplaysettings.Inthiscasetheresultmightbeablackscreen!

Page 448: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Lighting

Scenesyoudrawwiththefunctionsabovelookratherflatbecausethereisnolight.Thecolorifthefacesisequal,independentoftheirorientation.Tocreatemorerealisticallylookingscenesyoumustenablelightingandplacelightsatthecorrectplaces.Creatingcorrectlylitscenesisnoteasybuttheeffectisverygood.

Toenablelightingyoucanusethefollowingfunction;

d3d_set_lighting(enable)Enablesordisablestheuseoflighting.

Whenusinglighting,foreachvertexofapolygonthecolorisdetermined.Next,thecolorofinternalpixelsisbasedonthecolorofthesevertices.Therearetwowaysthiscanbedone:Eitherthewholepolygongetsthesamecolor,orthecolorissmoothlyinterpolatedoverthepolygon.Defaultsmoothshadingisused.Thiscanbechangedusingthefollowingfunction:

d3d_set_shading(smooth)Setwhethertousesmoothshadingornot.

Touselightingyouobviouslyneedtodefinelights.Twodifferentlightsexist:directionallights(likethesun),andpositionallights.Lighthaveacolor.(Weonlysupportdiffuselight,notspecularreflection.)Thefollowingfunctionsexisttodefineanduselights:

d3d_light_define_direction(ind,dx,dy,dz,col)Definesadirectedlight.indistheindexofthelight(useasmallpositivenumber).(dx,dy,dz)isthedirectionofthelight.colisthecolorofthelight(oftenyouwanttousec_white.Thisfunctiondoesnotturnthelighton.d3d_light_define_point(ind,x,y,z,range,col)Definesapointlight.indistheindexofthelightuseasmallpositivenumber).(x,y,z)isthepositionofthelight.rangeindicatestillhowfarthelightshines.Theintensityofthelightwilldecreaseoverthisrange.colisthecolorofthelight.Thisfunctiondoesnotturnthelighton.

Page 449: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

d3d_light_enable(ind,enable)Enables(true)ordisables(false)lightnumberind.

Thewayanobjectreflectslightdependsontheanglebetweenthelightdirectionandthenormalofthesurface,thatis,thevectorpointingawayfromthesurface.Hence,tocreatelightedobjectsyouneednotonlyprovidethepositionoftheverticesbutalsotheirnormals.Forthisfouradditionalfunctionsareavaliabletodefinetheverticesofprimitives:

d3d_vertex_normal(x,y,z,nx,ny,nz)Addvertex(x,y,z)totheprimitive,withnormalvector(nx,ny,nz).d3d_vertex_normal_color(x,y,z,nx,ny,nz,col,alpha)Addvertex(x,y,z)totheprimitive,withnormalvector(nx,ny,nz),andwithitsowncolorandalphavalue.d3d_vertex_normal_texture(x,y,z,nx,ny,nz,xtex,ytex)Addvertex(x,y,z)totheprimitive,withnormalvector(nx,ny,nz),andwithposition(xtex,ytex)inthetexture,blendingwiththecolorandalphavaluesetbefore.d3d_vertex_normal_texture_color(x,y,z,nx,ny,nz,xtex,ytex,col,alpha)

Addvertex(x,y,z)totheprimitive,withnormalvector(nx,ny,nz),andwithposition(xtex,ytex)inthetexture,blendingwithitsowncolorandalphavalue.

Notethatforthebasicshapesthatyoucandrawthenormalsareautomaticallysetcorrectly.

Page 450: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Creatingmodels

Whenyouneedtodrawlargemodelsitisratherexpensivetocallallthedifferentdrawingfunctionsagainandagainineverystep.Toavoidthisyoucancreatemodels.Amodelconsistsofanumberofdrawingprimitivesandshapes.Onceamodeliscreatedyoucandrawitatdifferentplaceswithjustonefunctioncall.Modelscanalsobeloadedfromafileorsavedtoafile.

Beforegivingthedifferentfunctionsavailablethereisoneimportantpoint:thehandlingoftextures.Asdescribedearlier,texturearetakenfromspritesandbackgrounds.Theindicesofthetexturescanbedifferentatdifferentmoments.Asaresultmodelsdonotcontainanytextureinformation.Onlywhenyoudrawamodelyouprovidethetexture.Soyoucanonlyuseonetextureinamodel.Ifyouneedmoretexturesyoumusteithercombinetheminone(andcarefullydealwiththetexturecoordinates)oryoumustusemultiplemodels.Theadvantageofthisisthatyoucandrawthesamemodeleasilywithdifferenttextures.

Forcreating,loading,saving,anddrawingmodels,thefollowingfunctionsexist:

d3d_model_create()Createsanewmodelandreturnsitsindex.Thisindexisusedinallotherfunctionsdealingwithmodels.d3d_model_destroy(ind)Destroysthemodelwiththegivenindex,freeingitsmemory.d3d_model_clear(ind)Clearsthemodelwiththegivenindex,removingallitsprimitives.d3d_model_save(ind,fname)Savesthemodeltotheindicatedfilename.d3d_model_load(ind,fname)Loadsthemodelfromtheindicatedfilename.d3d_model_draw(ind,x,y,z,texid)Drawsthemodelatposition(x,y,z).texidisthetexturethatmustbeused.Use-1ifyoudonotwanttouseatexture.Ifyouwanttorotateorscalethemodelyoucanusethetransformationroutinesdescribedbefore.

Page 451: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Foreachprimitivefunctionthereisanequivalenttoaddittoamodel.Thefunctionshavethesameargumentsasbeforeexceptthateachhasafirstargumenttheindexofthemodel,andnotextureinformationisprovided.

d3d_model_primitive_begin(ind,kind)Addsa3Dprimitivetothemodeloftheindicatedkind:pr_pointlist,pr_linelist,pr_linestrip,pr_trianglelist,pr_trianglestriporpr_trianglefan.d3d_model_vertex(ind,x,y,z)Addvertex(x,y,z)tothemodel.d3d_model_vertex_color(ind,x,y,z,col,alpha)Addvertex(x,y,z)tothemodel,withitsowncolorandalphavalue.d3d_model_vertex_texture(ind,x,y,z,xtex,ytex)Addvertex(x,y,z)tothemodelwithposition(xtex,ytex)inthetexture.d3d_model_vertex_texture_color(ind,x,y,z,xtex,ytex,col,alpha)

Addvertex(x,y,z)tothemodelwithtextureandcolorvalues.d3d_model_vertex_normal(ind,x,y,z,nx,ny,nz)Addvertex(x,y,z)tothemodel,withnormalvector(nx,ny,nz).d3d_model_vertex_normal_color(ind,x,y,z,nx,ny,nz,col,alpha)Addvertex(x,y,z)tothemodel,withnormalvector(nx,ny,nz),andwithitsowncolorandalphavalue.d3d_model_vertex_normal_texture(ind,x,y,z,nx,ny,nz,xtex,ytex)

Addvertex(x,y,z)tothemodel,withnormalvector(nx,ny,nz),withtextureposition.d3d_model_vertex_normal_texture_color(ind,x,y,z,nx,ny,nz,xtex,ytex,col,alpha)

Addvertex(x,y,z)tothemodel,withnormalvector(nx,ny,nz),withtextureandcolorvalues.d3d_model_primitive_end(ind)Endthedescriptionoftheprimitiveinthemodel.

Besidesprimitivesyoucanalsoaddbasicshapestothemodels.Againthefunctionslookalmostthesamebutwithamodelindexandwithouttextureinformation:

d3d_model_block(ind,x1,y1,z1,x2,y2,z2,hrepeat,vrepeat)Addsablockshapetothemodel.d3d_model_cylinder(ind,x1,y1,z1,x2,y2,z2,hrepeat,vrepeat,closed,steps)

Addsacylindershapetothemodel.d3d_model_cone(ind,x1,y1,z1,x2,y2,z2,hrepeat,vrepeat,closed,steps)

Addsaconeshapetothemodel.

Page 452: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

d3d_model_ellipsoid(ind,x1,y1,z1,x2,y2,z2,hrepeat,vrepeat,steps)

Addsaellipsoidshapetothemodel.d3d_model_wall(ind,x1,y1,z1,x2,y2,z2,hrepeat,vrepeat)Addsawallshapetothemodel.d3d_model_floor(ind,x1,y1,z1,x2,y2,z2,hrepeat,vrepeat)Addsafloorshapetothemodel.

Usingmodelscanconsiderablespeedupthegraphicsinyour3Dgamesandyoushouldusethemwheneveryoucan.

Page 453: Game Maker Helpavailable to control all aspects of your game. The following topics exist in this section: Language overview Computing things Game play User interaction Game graphics

Finalwords

The3DfunctionsinGameMakercanbeusedtomakesomenice3Dgames.However,theyarelimitedinfunctionalityandstillleavequitealotofworktoyou.Don'texpectthatyoucanmakeyourownQuakewithit.GameMakerisandremainsprimarilyapackageformaking2-dimensionalgames.