The Global Game Object

G - Description

G is the global game object, and it does a couple of things.

First, it creates as a global name space for all game related variables, functions and objects. This name space isolates GMP (and your game) under the umbrella of one global variable, 'G'.

This isolation is important in a JavaScript program, because it greatly reduces the chance of conflicts with common JavaScript libraries such as YUI, jQuery, MooTools and prototype.

Second, G is the actual 'engine' of your game. It has a central game loop, and performs basic management of all logic and objects inside your game.

You can think of G as a really basic game, which only needs the addition of your 'play' logic and pretty graphics to make it fun.

Variables

G.id, G.x, G.y, G.z, G.on, G.CO & G.tag (type: various)

These variables make G behave like a 'root' Gob. They are managed automatically, so there's no need to touch them.

You can find out more about these by reading the corresponding definitions in the G.Gob API section.

G.loopReference (type: object)

G.loopReference tracks the game loop setTimeout reference. There's no need to touch this.

G.iteration (type: int)

G.iteration is the current game loop iteration, set automatically in G.masterLoop(). This variable can be useful in timing and sequencing calculations.

G.interval (type: int)

G.interval is the number of milliseconds between game loop iterations, and it defaults to 40 (25 loops per second).

This value doesn't normally need to be changed, as 25 frames per second looks good on most computers, but feel free to set it to any whole number.

Setting it lower/higher can be quite helpful during development and testing.

Note that if the value is too low, game play will stutter, especially on older computers.

G.paused (type: boolean)

G.paused is a boolean that is set with G.pause()/G.unpause().

It suspends execution of 'in-game' functions: preAI and postAI hooks, as well as the main AI function. Note that system and stop hooks are still called.

G.hooks (type: object)

G.hooks is an object containing all game hooks, organized into 4 sub-sets: preAI, postAI, system, and stop.

A 'hook' is just a way to call a function inside the game loop, and we call such functions 'hooks' for short. Hooks within a given sub-set do not fire in any particular sequence.

Hooks are set with G.addHook()/G.deleteHook().

G.hooks.preAI (type: object) & G.hooks.postAI (type: object)

G.hooks.preAI and G.hooks.postAI functions are called before and after the main Block AI function (respectively), and aren't run if the game is paused.

Use these sets for pre- and post- processing logic that must occur outside the main Block AI function.

G.hooks.system (type: object)

System hooks are run after postAI hooks, and will run even if the game is paused.

Use this set for hooks that must execute even if the game is paused (for instance, certain animation or menu event functions). GMP uses this set for syncing mouse and keyboard state.

G.hooks.stop (type: object)

Stop hooks are run when the window.unload event fires; i.e., when a player leaves the page.

If you add a custom browser event to the game page's DOM, then you should also add a function to G.hooks.stop that releases that event handler.

GMP adds stop hooks for the mouse and keyboard event handlers, so you can look at them as examples.

G.S (type: object)

G.S is for storing all your global game state -- things like high scores, current level, # of lives, and reference arrays (eg, color tables).

GMP doesn't do any housekeeping with G.S, so you can safely put whatever you want in it.

State variables are often set directly, eg. 'G.S.hiScore=12345;', and can also be set in a batch using G.setState().

To reset G.S, simply assign a new object to it (empty or otherwise), eg, G.S={x:4}; or G.S={};

To delete a member variable from G.S, use the delete keyword, eg, delete G.S.hiScore

G.B (type: object)

G.B is an object containing the set of all Blocks in the game. Blocks are referenced by ID, and are added with G.makeBlock().

G.cBid (type: string)

G.cBid is the ID of the currently loaded Block, and is set by G.loadBlock().

The currently loaded Block is the only Block active in the game loop. Its AI function is called on every game loop iteration, right after preAI hooks and just before postAI hooks.

You might access this variable directly if your game has multiple Blocks and you are swapping them frequently (such as with a crossfade, menus, bonus screens, etc).

G.lBid (type: string)

G.lBid is the ID of the last loaded Block, and is set by G.loadBlock().

You might access this variable directly when switching back to your main Block after loading a temporary Block, like a menu or bonus screen.

G.O (type: object)

G.O is an object containing the set of all Gobs (game objects) in your game. Gobs are referenced by ID, and are added automatically when they are created.

This object is useful for quick global access to specific Gobs, or for performing batch operations on all Gobs in your game.

G.F (type: object)

G.F is an object for storing your game functions. Functions are referenced by name, and are added manually.

G.F is for convenience only, providing an identifiable name space for functions. For example: G.F.moveSprite = function (Sprite, newPos) { // some code to move 'Sprite' to 'newPos' }; The above example is clearly identifiable as a function local to your game, and not the GMP API:

G.cookieId (type: string)

G.cookieId is the name of the web browser cookie used to store your game's serialized G.cookies object.

G.cookieId defaults to 'G', and can be changed manually at any time. This makes it easy to use multiple cookies.

If you are using cookies in your game (they're good for storing high scores, current level, etc.), then you may want to change the value of G.cookieId to the name of your game, thus avoiding collisions with other games.

G.cookies (type: object)

G.cookies is an object containing the set of variables stored as cookie data in the web browser. Variables can be added and deleted to this set manually at any time, eg, 'G.cookies.hiScore=1000;'.

This object can also be loaded from, and saved to, the web browser cookie using G.loadCookie(), G.saveCookie().

To reset G.cookies, simply assign a new object to it (empty or otherwise), eg, G.cookies={x:4}; or G.cookies={};

To delete a member variable from G.cookies, use the delete keyword, eg, delete G.cookies.hiScore;

G.tmp (type: object)

G.tmp is a central storage object for any temporary values.

There's no garbage collection on this object, it is merely an identifiable container, provided for convenience.

G.mediaURL (type: string)

G.mediaURL is a string for storing the URL path to media files used in a game.

This is a convenience variable that makes it easy to set/change the URL used to find images used by Gobs. It is not used automatically, you must use it explicitly.

If your game has Gobs with the src attribute (i.e., images), then you can prefix the value of the src with G.mediaURL. E.g.: G.O.someGob.setVar({src:G.mediaURL + 'spaceship.gif'});

Be default, G.mediaURL is an empty string, so the images will be looked for in the same directory as the HTML page containing the game. Valid values can be any string that will be interpreted as a URL. For example, 'http://example.com/path/to/media/' or '/path/to/media/' should work fine.

Use this variable If your game is going to be embedded in an HTML page that is stored in a different directory from your game images.

Methods

Note: many of the following methods return an object instead of returning nothing. The returned object is often the parent object, or it may be 'G'. Doing this allows for method chaining, which can lead to compact code. The tutorial has examples that use chaining.

G.masterLoop() (returns G)

G.masterLoop() is the actual game loop function in the engine.

A game loop is the central structure in a game engine. Basically, the game engine's job is to call a sequence of functions, over and over again, on a regular interval. We call this behaviour a 'game loop', because the game engine is looping over the same set of functions every time.

Most of the functions executed in the game loop are written by the game developer.

Once started, it calls itself with setTimeout() using an interval of G.interval milliseconds.

Its purpose is simple: execute several sets of game code functions on a regular interval, and in a specific sequence. It also increments G.iteration once per loop.

The set of game code functions are executed in this order:

  • all preAI hooks (in no particular order)
  • the current Block AI function
  • all postAI hooks (in no particular order)
  • all system hooks (in no particular order)
If the game is paused (G.paused==1), then only system hooks are called.

G.masterLoop() is bootstrapped automatically in the GMP file, and never needs to be called inside game code.

G.addHook(name, fn, type) (returns G)

G.addHook(name, fn, type) adds a function to a set of hooks.

This function takes 3 arguments: the name of the hook, the hook function, and the set to which is to be added (i.e., its 'type'). Valid types are: 'preAI', 'postAI', 'system' and 'stop'.

There are several calls to this function in the GMP code that you can use for reference.

See G.masterLoop(), and G.hooks for more details about hook functions.

G.deleteHook(name, type) (returns G)

G.deleteHook(name, type) deletes a function from a set of hooks.

It takes 2 arguments: the name of the hook and the set (i.e., 'type') which contains it. Valid types are: 'preAI', 'postAI', 'system' and 'stop'.

See G.masterLoop(), and G.hooks for more details about hook functions.

G.pause() (returns G)

G.pause() is a convenience function for setting G.paused=1.

See G.masterLoop(), and G.paused for more details about pause behaviour.

G.unpause() (returns G)

G.unpause() is a convenience function for setting G.paused=0.

See G.masterLoop(), and G.paused for more details about pause behaviour.

G.makeBlock(id, load) (returns G)

G.makeBlock(id, load) instantiates a new G.Block object using the supplied ID and load function.

The ID is required, and should be a descriptive string. For games with only one Block object, the convention is to give it an id of 'main'.

The load function is optional (since it can be set separately), but can facilitate chaining.

G.makeBlock() also registers the Block in G.B, so using this function is recommended rather than instantiating Blocks directly.

G.loadBlock(id) (returns G)

G.loadBlock(id) is used to switch between Blocks.

It unloads the current Block, calling that Block's unload function and setting G.lBid to its ID (G.cBid).

It then loads the requested Block by setting G.cBid to the passed ID parameter, and then calling its load function.

Note that the default unload function behaviour is to turn off all of a Block's Gobs. If you don't want that behaviour on a Block, you will need to overwrite that Block's unload function.

G.setState(O) (returns G)

G.setState(O) adds the members of object 'O' to the G.S object.

If a member of O exists in G.S, then it over-writes the existing value, otherwise it just adds it.

See G.S for more details.

G.makeGob(id,parentGob, tagName, parentTag) (returns new Gob)

G.makeGob(id, parentGob, tagName, parentTag) instantiates a new G.Gob object using the supplied parameters.

The ID is required, and must be a string. It must be a globally unique Gob ID; if it isn't, the existing Gob with that ID will be destroyed and replaced with this new Gob.

The parentGob is optional, and must be a Gob object reference. It defaults to G, but will often be set to a container Gob.

The tagName is optional, and must be a string. It can be the name of almost any valid HTML element. It defaults to 'DIV'. if you supply this parameter, you must also explicitly supply a valid parentGob parameter.

The parentTag is optional, and must be a DOM tag reference. It can be any tag in the current document. It defaults to the DOM tag of parentGob. if you supply this parameter, you must also explicitly supply valid parentGob and tagName parameters.

Some common examples: G.makeGob('viewport'); G.makeGob('hiScore', G.O.scoreboard); G.makeGob('alien5', G.O.viewport, 'IMG'); G.makeGob('game', G, 'DIV', document.getElementById('someDIV'));

This function is the recommended method for creating new Gobs, because it adds the new Gob to the global Gob set (G.O), and allows for method chaining.

See G.Gob for more details about the structure and relationships of Gobs and tags.

G.deleteGob(id) (returns G)

G.deleteGob(id) deletes the Gob identified by the supplied ID. The ID is required, and must be a string.

This function will safely delete simple Gobs, so that the id can be reused.

For more complex Gobs, consider the following additional steps:

  • If you have added events (eg, onclick, onmousedown, etc) to the Gob's tag, then you must set them to NULL before calling G.deleteGob(id). For example: G.O[id].tag.onclick=null; G.deleteGob(id); For reference, GMP doesn't add events to Gob tags. You would have added them yourself in game code.
  • If you want to delete a Gob with child Gobs (eg, a viewport or layer), then delete the child Gobs first. Gobs track their children in G.Gob.CO (Child Objects), so a simple loop will give you direct access. For example: for ( var childGobID in G.O[id] ) { delete G.O[id].CO[childGobID]; } G.deleteGob(id);
  • If you have created custom Gob references, they must be deleted before the browser can perform garbage collection on the object. G.deleteGob(id) deletes references to Gobs inside G.O, G.CO, G.Block.O and G.Gob.CO. If you have other references to the Gob, it is highly recommended that you delete them as well after/before you run G.deleteGob(id). For example: delete G.S.customGobSet[id]; G.deleteGob(id);

G.loadCookies() (returns G)

G.loadCookies() loads and parses a web browser cookie containing a serialized G.cookies object.

G.cookieId contains the name of the web browser cookie that is to be loaded.

The parsed cookie data is added to the current G.cookies object. Similarly named object members are over-written; otherwise existing members are preserved.

See G.saveCookies() and G.cookies for more details.

G.saveCookies() (returns G)

G.saveCookies() serializes and saves the G.cookies object to a web browser cookie. It returns G.

G.cookieId contains string used to name the web browser cookie.

The serialized G.cookie object over-writes any existing cookie of the same name. For simplicity, the new cookie is given a site-wide scope, and far-future expiry date.

See G.loadCookies() and G.cookies for more details.

G.dirY(degrees) (returns float)

G.dirY(degrees) returns the y-axis component of a given direction's unit vector.

The supplied direction must be in degrees, and can be any int or float value. The return value will be a float between 0 and 1, inclusive, and is fixed at 8 decimal places, so that a degrees argument equivalent to 180 returns 0 instead of a very small non-zero number.

If you look at the code for G.dirY(), you will see that the computed value is multiplied by -1. This is done to synchronize the GMP coordinate system with your web browser's cartesian plane, where Y values increase as you move down the page.

This function is very useful in motion calculations, and is used inside GMP by G.Gob.fixIntersection().

For reference, direction increases in a counter-clockwise manner, and 0º corresponds to 3 o'clock on a rotary clock face.

G.dirX(degrees) (returns float)

G.dirX(degrees) returns the x-axis component of a given direction's unit vector.

The supplied direction must be in degrees, and can be any int or float value. The return value will be a float between 0 and 1, inclusive, and is fixed at 8 decimal places, so that a degree argument equivalent to 90 or 270 return 0 instead of a very small non-zero number.

This function is very useful in motion calculations, and is used inside GMP by G.Gob.fixIntersection().

For reference, direction increases in a counter-clockwise manner, and 0º corresponds to 3 o'clock on a rotary clock face.

G.dirXY(x, y) (returns float)

G.dirXY(x,y) returns the direction, in degrees, of any (x,y) vector.

The return value will be in the set [0,360). The parameters x and y do not need to be normalized.

This function is very useful in motion calculations, and is used inside GMP by G.Gob.fixIntersection().

Supporting In-line Code

There is an in-line chunk of code immediately after the G method definitions. This code makes sure all stop hooks are called when the player leaves the web page. It also creates a wrapper around any existing window.onunload function, so that it isn't over-written.

Here's the code:

if (typeof window.onunload == 'function') G.oldUnload = window.onunload; else G.oldUnload = function () {}; window.onunload = function () { G.oldUnload(); for (var i in G.hooks.stop) G.hooks.stop[i](); };

Previous: GMP Overview Next: G.Block