http://lagacode.com
August 2012
Lagacode SDK
Introduction .................................................................................................................................................. 1 The Lagacode Game Object Model ............................................................................................................... 2 Lagacode Package Structure ......................................................................................................................... 5 Playlist ........................................................................................................................................................... 6 Level .............................................................................................................................................................. 7 Item ............................................................................................................................................................. 11 Sprite ........................................................................................................................................................... 18 Event Handlers ............................................................................................................................................ 19 Event Handler Javascript Definitions .......................................................................................................... 19 Mouse/Touch Events .................................................................................................................................. 21 Keyboard Events ......................................................................................................................................... 22 Images ......................................................................................................................................................... 23 Sounds ......................................................................................................................................................... 23 Strings ......................................................................................................................................................... 23
Introduction
Lagacode is a Javascript/JSON-powered game engine that enables rapid game development, iteration and distribution. Lagacode games are simultaneously available on HTML5-capable web browsers as well as mobile1 (Android, iOS, Windows). This document explains the Lagacode game model, how game levels are constructed and the underlying API that powers Lagacode games.
An Android prototype is currently available and iOS & Windows versions are currently in the design phase.
Page 1
http://lagacode.com
August 2012
next
Level
Items
Images
Sounds
Strings
Page 2
http://lagacode.com
August 2012
The goal for level/item inheritance is to enable easy code reuse. Imagine developing a game where the background of each level is similar or a game that uses bouncing balls with the same characteristics (event handling, size, etc) but you want to make them different colors. More immediately, the JSON for a level definition supports defining a list of items to be placed in the level before gameplay begins. If the items are defined separately from the games levels, all that is needed to place them in a level is a parent name and an x,y coordinate pair.
Event Handlers
Most Javascript code for Lagacode games should be implemented in the form of event handlers. Levels and Items have a set of events associated with their lifecycle (level start, level end, item hit, etc.). Event handler methods for mouse/touch events as well as key events are also provided. Game developers can also define their own event interfaces and raise events on item or level event busses. Please see the documentation below for how to declare event handlers as well as the specific level, item, touch and key events raised.
Page 3
http://lagacode.com
August 2012
Elapsed time > 1/60th second? Yes Advance Level physics by one clock tick Fire any onItemHit() events due to collisions For each item, fire onItemTickEvent() Fire onLevelTick() Event Decrement Elapsed time by 1/60th sec Render Level
No
No
Level Complete?
Yes
Done
Page 4
http://lagacode.com
August 2012
Package Forking
One of the goals for building the Lagacode developer community is the sharing of packages, both as imports as well as forking. A package fork is a deep copy of all the elements in the package. The main use case for forking a package is to give a developer a quick way jumpstart game development. This is especially useful when one is starting out and trying to learn the SDK. Rather than coding a Hello World game from scratch, a forked copy of a sample game gives a developer a quick way to start playing around with the SDK and build on the work of others. In order for a Lagacode community member to fork a package developed by another community member, the package must be marked Public. Otherwise, it will be inaccessible for forking. Similarly, any package imports must also be public or the package will be unusable to other developers.
Package:FileName format
Files and other assets (sounds, images) are uniquely referenced via package:fileName format. That is, a resource locator for items within the Lagacode universe consists of a package name and file name delimited by a colon (:). For example, suppose your package is named MyPackage and you have an image named MyImage. You can reference the image as MyPackage:MyImage (no spaces). __pkg__ Identifier Lagacode packages are designed to be forked (cloned) to create new packages. We believe the best way to learn a new language or platform is to dig in to someone elses code and change it. To aid this reuse, the package part of the package:fileName format can be replaced with __pkg__ (two underscores on either side of pkg). When packages are loaded, the __pkg__ character sequence is replaced with the current package name. In the example above, MyPackage:MyImage could be referenced as __pkg__:MyImage within the MyPackage package. The motivation for this macro replacement is to enable simpler package forking. A package that consistently uses the __pkg__ identifier can easily be forked without any code modifications in the new package.
Page 5
http://lagacode.com
August 2012
Playlist
A playlist is an ordered collection of levels.
JSON Properties
Name
nextPlaylist playlist[]
Type
String Array
Description
The name of a playlist, in package:fileName format, that will be played after this playlist is completed. Default is null. An ordered array containing the names of the levels, in package:fileName format, to be played. The package to which the playlist belongs must have access (import if necessary) all the packages of the levels listed in the array. A valid, non-empty array declaration is required for the playlist to be valid.
Page 6
http://lagacode.com
August 2012
Level
JSON Properties
Name
parent helpLevel
Type
String String
Description
The name of the of the parent level, if any, in package:fileName format. Default is null. The name of the help level, if any, in package:fileName format. The help level is displayed when a user selects the menu and then clicks on the help button. It is intended to instruct the user on game play. Default is null. Configuration object to be passed to each of the levels event handlers. Default is null. The width, in World units, of the display viewport. Note: 1 World unit is equivalent to 1 meter when used by the physics engine. Default value is 100 The height, in World units, of the display viewport. Note: 1 World unit is equivalent to 1 meter when used by the physics engine. Default value is 50. The center X coordinate, in World units, for the display viewport. Default is 0. The center Y coordinate, in World units, for the display viewport. Default is 0. The X component of the gravitational force for the World, in meters per seconds squared. Default is 0. The Y component of the gravitational force for the World, in meters per seconds squared. Default is 0. To simulate Earth gravity, a value of -9.8 (or something close like -10) should be used. An array containing item declarations to be placed in the level before the level event loop is started. Default is null An array of event handlers to be created for the level. See Event Handler JSON definition. Default is null The background color (in CSS/HTML format) of the level. Default value is black The color (in CSS/HTML format) of the info bar (level score, menu button, etc.). Default value is white
config viewportWidth
Object Number
viewportHeight
Number
itemDefs[] eventHandlers[]
Array Array
Page 7
http://lagacode.com
August 2012
Level Events
Name
onLevelStart(Object evtParms)
Description
Raised automatically when a level has been initialized and the event loop is about to commence. Called before item start events. Parameters: evtParms - null Raised automatically at each clock tick (1/60th of a second) of the event loop. Clock ticks are called after physics (movements, collisions) have been resolved and before items are rendered. Parameters: evtParms - null Raised manually by calling the _level objects done() method to indicate level play has completed. Parameters: evtParms null
onLevelTick(Object evtParms)
onLevelDone(Object evtParms)
Name
void addItem(Object itemDef)
Description
Adds an item to the level. Once added, the items onItemStart event is raised. Parameters: itemDef object containing the JSON definition of the item to be added. Adds an item to the level. Once added, the items onItemStart event is raised. Parameters: itemDefName string referencing the name item definition in package:fileName format. Removes an item from the level. Parameters: item the _item object which is to be dropped. _item is a property injected into Item event handlers (along with _game and _level). Sets the center point for the viewport. The default center is (0,0). Parameters: x, y the x and y coordinates (in world units). World coordinates are right-handed meaning that x units increase from left to right and y units increase from bottom to top. Retrieves the current center point for the viewport. Return Value an object with x and y properties representing the center point. For example: var center = this._level.getViewportXY(); alert('center is ' + center.x + ',' + center.y); Returns the number of tick events generated per second by the level. Default is 60 Return Value a number between 1 and 1,000.
void dropItem(item)
void setViewportXY(x, y)
XY getViewportXY()
Number getTickFrequency()
Page 8
http://lagacode.com
August 2012
Number getGlobalHighScore()
void done()
Sets the number of tick events generated per second by the level. Parameters: freq a number between 1 and 1,000 Returns the current score for the level. Return Value a number between 0 and 10,000 Sets the current score for the level. Parameters: score a number between 0 and 10,000 Returns the players highest score for the level. Note: high scores are retrieved asynchronously and may not be available when onStart() events are fired. Returns the highest score recorded for the level by any player. Note: high scores are retrieved asynchronously and may not be available when onStart() events are fired. Raises an event to the level. Parameters: eventType the type of event, possibly userdefined. Event listeners are attached to specific event types. Example value - Touch eventName the name of the event being raised. For example, Start eventParms event-specific parameters. Vary by event and can be null. Signals that the level is complete. The game event loop is stopped and the levels score is recorded. The game then moves to the next level in the playlist. Switch to a new level, possibly raising the onLevelDone() event for the current level. Parameters: playlistName the name of the playlist, in package:filename format, which contains the level. levelName the name of the level, in package:filename format, to be played. raiseDoneEvent a flag indicating whether or now the onLevelDone() event should be raised for the current level. Sets the levels background color. Parameters: color - the color (in CSS/HTML format) of the body. Transparent bodies should have a color of transparent. Default value is black Returns the levels background color. Displays a line of text in the console window of the development IDE. Has no effect if the game is being played outside the IDE. Parameters: text - the string to be displayed. Return Value None
Page 9
http://lagacode.com
August 2012
Plays a named sound immediately. soundName the name of the sound in package:filename format volume (optional) a value between 0 and 1 indicating how loud to play the sound. Default is 0.5 Return Value None Plays a named sound immediately with possibly different left and right channel volumes. soundName the name of the sound in package:filename format leftVolume a value between 0 and 1 indicating how loud to play the sound in the left channel. rightVolume a value between 0 and 1 indicating how loud to play the sound in the left channel. Return Value - None
Page 10
http://lagacode.com
August 2012
Item
JSON Properties
Name
parent config bodyType
Type
String Object static | kinematic | dynamic Boolean
Description
The name of the of the parent item, if any, in package:fileName format. Default is null. Configuration object to be passed to each of the items event handlers. Default is null. Please refer to the Box2D Manual for a full description of static, kinematic and dynamic bodies. Note that static and kinematic bodies do not collide with each other. Default value is static Sometimes game logic needs to know when two fixtures overlap yet there should be no collision response. This is done by using sensors. A sensor is a fixture (item) that detects collision but does not produce a response. Default value is: false The physical shape of the item. Currently, we only support circles and rectangles. Also, we only support one fixture per body (in Box2D terminology) Default value is rectangle From the Box2D Manual: You may want a rigid body, such as a character, to have a fixed rotation. Such a body should not rotate, even under load The fixed rotation flag causes the rotational inertia and its inverse to be set to zero. Default value is false. Please see the Box2d Manual for a detailed description of the bullet attribute. In a nutshell, setting bullet to true helps ensure that small, fast-moving objects do not tunnel thru other objects and avoid collision detection. There is a performance cost for this, so set this attribute to true judiciously. Default value is false. From the Box2d Manual: Damping is used to reduce the world velocity of bodies. Damping is different than friction because friction only occurs with contact. Damping is not a replacement for friction and the two effects should be used together. Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity meaning full damping. Normally you will use a damping value between 0 and 0.1. Default value is 0.01
sensor
shape
fixedRotation
bullet
Boolean
angularDamping
Number
Page 11
http://lagacode.com
August 2012
color
String
height
Number
density
Number
restitution
Number
friction
Number
Number
From the Box2d Manual: Damping is used to reduce the world velocity of bodies. Damping is different than friction because friction only occurs with contact. Damping is not a replacement for friction and the two effects should be used together. Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity meaning full damping. Normally you will use a damping value between 0 and 0.1. I generally do not use linear damping because it makes bodies look floaty. Default value is 0 The color (in CSS/HTML format) of the body. Transparent bodies should have a color of transparent. Default value is transparent Level of opacity/transparency of item. 0 is transparent, 1 is completely opaque. Default value is 1 The radius, in world units, of a circle shape. Not used by rectangle shapes. Default value is 0 The (full) width of a rectangle shape. Not used by circle shapes. This use differs from the Box2D API, which defines rectangles using half the width. Default value is 0 The (full) height of a rectangle shape. Not used by circle shapes. This use differs from the Box2D API, which defines rectangles using half the height. Default value is 0 From the Box2d Manual: The fixture density is used to compute the mass properties of the parent body. The density can be zero or positive. You should generally use similar densities for all your fixtures. Default value is 1 From the Box2d Manual: Restitution is used to make objects bounce. The restitution value is usually set to be between 0 and 1. Consider dropping a ball on a table. A value of zero means the ball won't bounce. This is called an inelastic collision. A value of one means the ball's velocity will be exactly reflected. This is called a perfectly elastic collision. Default value is 0.3 From the Box2d Manual: Friction is used to make objects slide along each other realistically. Box2D supports static and dynamic friction, but uses the same parameter for both. Friction is simulated accurately in Box2D and the friction strength is proportional to the normal force (this is called Coulomb friction). The friction parameter is usually set between 0 and 1, but can be any non-negative value. A friction value of 0 turns off friction and a value of 1 makes the friction strong. Default value is 0.3 The x coordinate, in world units, of the item. Note that world coordinates are a right-handed system (with z-axis pointing towards us) where x increases from left to right and y increases from bottom to top. Default value is 0
Page 12
http://lagacode.com
August 2012
zIndex
Number
angle
Number
The y coordinate, in world units, of the item. Note that world coordinates are a right-handed system (with z-axis pointing towards us) where x increases from left to right and y increases from bottom to top. This differs from typical graphics systems (left-handed) where y increases from top to bottom. Default value is 0 The stack order of items during rendering. As with CSS, an item with a higher z index will overlap an item with a lower z-index. Default value is 0 The rotation of the item in radians. In the world coordinate system, increasing the angle rotates the item counterclockwise. Default value is 0 Text to display over this item. Default is null Color of the text to be displayed. Default is black. Alignment of the text (in HTML/CSS format). Default is center The width, in world units, that a capital A should be. For example, if the levels viewport width is 100 world units, then a textCharWidth of 2 means 50 As will fit across the viewport horizontally. Default is 2.5. The name of the font to display. Default is Calibri A number between 0 and 1 (inclusive) indicating the alpha level of the text. 0 is completely transparent and 1 indicates completely opaque. Default value is 1. List of sprites attached to this item. May be null if no sprites are used. See Sprite JSON definition. Default is null. An array of event handlers to be created for the item. See Event Handler JSON definition. Default is null
textFont textAlpha
String Number
sprites[] eventHandlers[]
Array Array
Page 13
http://lagacode.com
August 2012
Item Events
Event handler type Item
Name
onItemStart(evtParms)
Description
Raised automatically after an item has been created and before the next event loop clock tick. Parameters: evtParms - null Raised automatically at each clock tick (1/60th of a second) of the event loop. Clock ticks are called after physics (movements, collisions) have been resolved and before items are rendered. Parameters: evtParms - null Raised automatically by the physics engine when two items collide. Two onItemHit events are raised. Assume item A hits item B, then an onItemHit event is raised to item A passing in itemB as a parameter and an onItemHit event is raised to item B passing in item A as a parameter. Parameters: evtParms the _item object of the item with which this item collided
onItemTick(evtParms)
onItemHit(evtParms)
Page 14
http://lagacode.com
August 2012
Location
Name
Number getRadius () Number getWidth () Number getHeight () Number getAngle () void setAngle (Number radians) XY getPosition()
Description
Returns the radius, in world coordinates, of a circle item. Returns the width, in world coordinates, of a rectangle item. Returns the height, in world coordinates, of a rectangle item. Returns the items angle in radians. Sets the items angle Parameters: angle the radians value of the angle Retrieves the current center point for the item. Return Value an object with x and y properties representing the center point. For example: var pos = this._item.getPosition(); alert('Position is ' + pos.x + ',' + pos.y); Sets the center point for the item. Parameters: x, y the x and y coordinates (in world units). World coordinates are right-handed meaning that x units increase from left to right and y units increase from bottom to top. Sets the center point and angle of the item. This is a way to move an item without using forces or setting a velocity. Item velocity is preserved. Parameters: x, y the x and y coordinates (in world units). World coordinates are right-handed meaning that x units increase from left to right and y units increase from bottom to top. angle the radians value of the items angle
Page 15
http://lagacode.com
August 2012
Physics
The _item property exposes a number of physics-related methods. For an explanation of the methods, please see the Box2d Manual.
Name
void applyAngularImpulse (Number impulse) void applyForce:(Number force_x, Number force_y, Number point_x, Number point_y) void applyLinearImpulse (Number impulse_x, Number impulse_y, Number point_x, Number point_y) void applyTorque (Number torque) Number getAngularDamping () void setAngularDamping (Number angularDamping) Number getAngularVelocity () void setAngularVelocity (Number angularVelocity) Number getInertia () XY getCenterOfMass () Number getMass () boolean getBullet() void setBullet (Boolean flag) void setFixedRotation (Boolean flag) Number getLinearDamping () void setLinearDamping (Number linearDamping) XY getLinearVelocity () void setLinearVelocity (Number x, Number y)
Description
Page 16
http://lagacode.com
August 2012
Display
Name
setColor(String color) getColor() setText (String text) getText () setText Color(String textColor) getText Color() setText Align(String textAlign) getText Align() setText Alpha(Number textAlpha) getText Alpha() putSprite (String spriteName, Object spriteDef)
Description
Sets the color of the shape (in HTML/CSS format). Returns the current color of the shape. Sets the text to display over this item. Returns the current text for the item. Sets the color of the text to be displayed (in HTML/CSS format). Returns the current text color of the item. Sets the alignment of the items text (in HTML/CSS format). Returns the alignment of the items text. Sets the alpha level of the items text. Retrieves the alpha level of the items text. Attaches (or updates) a named sprite to the item. Parameters: spriteName the name of the sprite spriteDef a sprite definition (see JSON description below). Detaches (removes) a named sprite from an object. The sprite will no longer be displayed. Retrieves a named sprite from the object. Can be used in conjunction with putSprite to update a sprites position/appearance/etc and enable animation. Return value: a sprite definition.
Miscellaneous
Name
raiseEvent (String eventType, String eventName, Object eventParms)
Description
Raises an event to the item. Parameters: eventType the type of event, possibly user-defined. Event listeners are attached to specific event types. Example value Touch eventName the name of the event being raised. For example, Start eventParms event-specific parameters. Vary by event and can be null.
Page 17
http://lagacode.com
August 2012
Sprite
A sprite is a scaled image that is connected to an item. An item can have zero or more sprites connected to it.
JSON Properties
Name
imageName tileX tileY width height
Type
String Number Number Number Number
Description
The name of the image, in package::fileName format, to be displayed. The x offset of which tile in the image to be used. Default is 0. The y offset of which tile in the image to be used. Default is 0. The width of the sprite in world units. Indicates how the sprite is scaled horizontally. Default value is 5. The height of the sprite in world units. Indicates how the sprite is scaled vertically. A value of -1 indicates the sprite should maintain its aspect ratio. Default value is -1. The offset, in world units, of the center of the sprite relative to the x position of the item. That is, a value of 0 indicates the horizontal center of the sprite matches that of the underlying item. Default value is 0. The offset, in world units, of the center of the sprite relative to the y position of the item. That is, a value of 0 indicates the vertical center of the sprite matches that of the underlying item. Default value is 0. The rotation of the sprite in radians. Default value is 0. A number between 0 and 1 (inclusive) indicating the alpha level of the image. 0 is completely transparent and 1 indicates completely opaque. Default value is 1.
Number
Number
angle alpha
Number Number
Page 18
http://lagacode.com
August 2012
Event Handlers
Event handlers, within Level and Item definitions must be declared in the following manner. { handler: "handlerObjectName ", types: ["eventType1 ", "eventType2 ", ] } The handlerObjectName is the name of the Javascript object that will be created and the eventTypes are the types of events the object should be contacted to handle. For example, assume a Javascript object called uiLaunchPad will handle both Item and Touch events. Its event handler declaration would look something like this: eventHandlers:[ { handler: "uiLaunchPad ", types : ["Touch ", "Item "], }]
A single item or level can have more than one event handler and a single event handler may handle events of more than one type. IMPORTANT: currently, an item or level can only have one handler for each type of event. What that means is that if a child item or level declares a handler for a specific type of event, it will effectively hide parent event handlers of the same event. We are considering easing this restriction and (as always) welcome feedback from the developer community.
Page 19
http://lagacode.com
August 2012
function myEventHandler(config) { this.firstTime = true; this.configThing = config.configThing; // handle the Level Start event this.onLevelStart = function(evtParms) { // add a property to the _level object. this._level.myGlobal = true; return true; // weve handled the event, do not pass it on }; // handle the Level Done event this.onLevelDone = function(evtParms) { return true; }; // handle the Level Tick event (a tick is 1/60th of a second) this.onLevelTick = function(evtParms) { // do something at each clock tick // assume that isDone is a Boolean indicating whether the level // is complete. if (isDone === true) { this._level.done(); // let the system know were done }
}
};
Page 20
http://lagacode.com
August 2012
Mouse/Touch Events
Mouse events and touch events are not differentiated. That means that mouse down/up/move events are treated identically to mobile touch down/up/move events. It also means that a full set of multitouch events are not supported to maintain compatibility with browser versions of games. Touch events are first fired on the item(s) (if any) at the point of event contact. If there is no item situated there or the items do not have a touch event handler or an items touch event handler returns false (ie/allows further event handlers to be fired), then the current levels touch event handler(s) will be called. Over & Out events are also supported and work in a similar manner to JavaScript mouseover and mouseout events, including event bubbling.
Name
onTouchStart(Object xy)
Description
Fires on a mouse down/touch start event. Parameters: xy an XY object indicating (in world coordinates) where the touch event occurred Fires on a mouse up/touch endevent. Parameters: xy an XY object indicating (in world coordinates) where the touch event occurred Fires on a mouse move/touch move event. Parameters: xy an XY object indicating (in world coordinates) where the touch event occurred Fires when a mouse pointer (or touch move) enters an object. Only fires on items. Parameters: o null Fires when a mouse pointer (or touch move) exits an object. Only fires on items. Parameters: o - null
onTouchEnd(Object xy)
onTouchMove(Object xy)
onTouchOver(Object o)
onTouchOut(Object o)
Page 21
http://lagacode.com
August 2012
Keyboard Events
Keyboard events can arise from actual keyboard events and can be simulated as well for devices that do not have keyboards. For example, a level can create items that handle Touch Start and End events to fire Key Down and Up events.
Name
onKeyDown(Object keyEvt)
Description
Fires when a key is depressed. May be fired multiple times if the user holds the key down for an extended period of time. Parameters: keyEvt a JSON object containing the following fields: keyCode: the integer value for the key. For a good discussion of JavaScript keyCode issues, please see http://www.javascripter.net/faq/keycodes.htm keyChar: the character value of the key. altKey: boolean flag indicating whether the Alt key is pressed. ctrlKey: boolean flag indicating whether the Ctrl key is pressed. shiftKey: boolean flag indicating whether the Shift key is pressed.
onKeyUp(Object keyEvt)
Fires when a depressed key is released. Parameters: keyEvt a JSON object containing the following fields: keyCode: the integer value for the key. For a good discussion of JavaScript keyCode issues, please see http://www.javascripter.net/faq/keycodes.htm keyChar: the character value of the key. altKey: boolean flag indicating whether the Alt key is pressed. ctrlKey: boolean flag indicating whether the Ctrl key is pressed. shiftKey: boolean flag indicating whether the Shift key is pressed.
Page 22
http://lagacode.com
August 2012
Images
Images are uploaded within the IDE. A single image may consist of multiple tiles. If so, the image is divided evenly based on the number of Horizontal Tiles (columns) and Vertical Tiles (columns) it contains. When uploading images, make sure you have the legal right to use the image and also make sure you assign the image appropriate attribution.
Sounds
Coming soon.
Strings
Coming soon.
Page 23