All classes that dispatch events inherit from EventDispatcher
. The target of
an event is a listener function and an optional data value.
When an event is dispatched, the registered function is called.
If the optional data value is given, it is used as a first parameter
while calling the listener function.
Event dispatching and event targets are the core part of the
Gideros event model. Different event types (such as Event.ENTER_FRAME
,
Event.TOUCHES_BEGIN
or Event.MOUSE_DOwN
)
flow through the scene tree hierarchy differently. When a touch or mouse event occurs,
Gideros dispatches an event object into the event flow from the root of the scene tree.
On the other hand, Event.ENTER_FRAME
event is dispatched to all Sprite
objects.
If you want to define a class that dispatches events, you can inherit your class
from EventDispatcher
.
-- example 1
ClassA = Core.class(EventDispatcher)
ClassB = Core.class(EventDispatcher)
function ClassA:funcA(event)
print("funcA", self, event:getType(), event:getTarget())
end
local a = ClassA.new()
local b = ClassB.new()
b:addEventListener("myevent", a.funcA, a) -- when b dispatches an "myevent" event,
-- a.funcA will be called with 'a'
-- as first parameter
b:dispatchEvent(Event.new("myevent")) -- will print "funcA"
-- example 2
Ball = Core.class(Sprite)
function Ball:onEnterFrame()
self:setX(self:getX() + 1)
end
ball = Ball.new()
ball:addEventListener(Event.ENTER_FRAME, ball.onEnterFrame, ball)
Registers a listener function and an optional data value so that the listener function is called when an event of a particular type occurs.
type: (string) The type of event. listener: (function) The listener function that processes the event. data: (optional) An optional data parameter that is passed as a first argument to the listener function.
EventDispatcher:removeEventListener
Removes a listener from the EventDispatcher
object. removeEventListener()
function expects
the same arguments with addEventListener()
to remove the event. If there is no matching listener
registered, a call to this function has no effect.
type: (string) The type of event. listener: (function) The listener object to remove. data: The data parameter that is used while registering the event.
EventDispatcher:addEventListener
Dispatches an event to this EventDispatcher
instance.
event: (Event) The `Event` object to be dispatched.
Checks if the EventDispatcher
object has a event listener registered for the specified type of event.
type: (string) The type of event.
A value of true
if a listener of the specified type is registered; false
otherwise.
The objects of Event
class contains information about an event that has occurred. Event
objects
are passed to event listeners when an event occurs.
Usually event objects contains specific additional information about the event that has occured. For example,
when an Event.MOUSE_DOWN
event occurs, x
and y
fields contain the coordinates:
function onMouseDown(event)
print(event.x, event.y)
end
mysprite:addEventListener(Event.MOUSE_DOWN, onMouseDown)
Users can create their own events and dispatch through the event mechanism:
local event = Event.new("myevent")
event.data1 = "12345"
event.data2 = "abcde"
mydispatcher:dispatchEvent(event)
Creates a new Event
object to be dispatched from an EventDispatcher
.
type: (string)
New Event
object.
Returns a string that represents the type of the event.
Type of event.
Returns the element on which the event listener was registered.
Target of event.
Disables the propagation of the current event in the scene tree hierarchy.
The Sprite
class is the base class for all objects that can
be placed on the scene tree. It is the basic scene tree building block.
A sprite can contain child sprites which makes the scene tree hierarchy. Transformations such as translation, rotation, scaling and color transforms propogates its effect to all of its children.
The drawing order is defined by the order of children. First child is drawn first and last child is drawn last. It is possible to change the drawing order by modifying the order of child list.
A Sprite
instance can exists without attaching the scene tree.
An unattached sprite can receive Event.ENTER_FRAME
event but
it will only receive mouse and touch events when it is
attached to the scene tree.
Adds a sprite as a child to this sprite. The child is
added as a last child of this Sprite
instance.
Sprites can have only one parent. Therefore if you add a child object that already has a different sprite as a parent, the sprite is removed from the child list of the other sprite and then added to this sprite.
child: (Sprite) The child sprite to add.
Adds a sprite as a child to this sprite. The child is added at the index position specified. Indices start from 1.
Sprites can have only one parent. Therefore if you add a child object that already has a different sprite as a parent, the sprite is removed from the child list of the other sprite and then added to this sprite.
child: (Sprite) The child sprite to add. index: (number) The index position to which the child is added.
Removes the specified child Sprite
instance from the child list of this Sprite
instance.
child: (Sprite) The child sprite to remove.
Removes the child Sprite
instance at the specifed index. Index of the first child is 1
and index of the last child can be get from Sprite:getNumChildren
function.
index: (number) The child index of the sprite to remove.
Determines whether the specified sprite is contained in the subtree of
this Sprite
instance.
child: (Sprite) The child object to test.
true
if the child object is contained in the subtree of this Sprite
instance, otherwise false
.
Converts the x,y coordinates from the global to the sprite’s (local) coordinates.
x: (number) x coordinate of the global coordinate. y: (number) y coordinate of the global coordinate.
Converts the x,y coordinates from the sprites’s (local) coordinates to the global coordinates.
x: (number) x coordinate of the local coordinate. y: (number) y coordinate of the local coordinate.
Returns the child Sprite
instance that exists at the specified index. First child is at index 1.
index: (number) The index position of the child object.
The child sprite at the specified index position.
Returns the index of the specified child sprite.
child: (Sprite) The child sprite to identify.
The index of the specified child sprite.
Returns the height of the sprite, in pixels. The height is calculated based on the bounds of the content of the sprite.
Height of the sprite.
Returns the width of the sprite, in pixels. The width is calculated based on the bounds of the content of the sprite.
Width of the sprite.
Returns the rotation of the sprite in degrees.
Rotation of the sprite.
Sets the rotation of the sprite in degrees.
rotation: (number) rotation of the sprite
Returns the horizontal scale of the sprite.
The horizontal scale (percentage) of the sprite.
Sets the horizontal scale of the sprite.
scaleX: (number) horizontal scale of the sprite
Returns the vertical scale of the sprite.
The vertical scale of the object.
Sets the vertical scale of the sprite.
scaleY: (number) vertical scale (percentage) of the object
Returns the horizontal and vertical scales of the sprite.
The horizontal and vertical scales of the sprite
Sets the horizontal and vertical scales of the sprite.
scaleX: (number) horizontal scale (percentage) of the object scaleY: (number, default = scaleX) vertical scale (percentage) of the object
Returns whether or not the sprite is visible. Child sprites that are not visible are also taken into consideration while calculating bounds.
A value of true
if sprite is visible; false
otherwise.
Sets whether or not the sprite is visible. Sprites that are not visible are also taken into consideration while calculating bounds.
visible: (bool) whether or not the sprite is visible
Returns the x coordinate of the sprite.
The x coordinate of the sprite
Sets the x coordinate of the sprite
x: (number) The new x coordinate of the sprite
Returns the y coordinate of the sprite.
The y coordinate of the sprite
Sets the y coordinate of the sprite.
y: (number) The new y coordinate of the sprite
Returns the x and y coordinates of the sprite.
The x and y coordinates of the sprite
Sets the x and y coordinates of the sprite.
x: (number) The new x coordinate of the sprite y: (number) The new y coordinate of the sprite
Sets the specified property of this sprite instance by its name. These names are supported:
"x"
"y"
"rotation"
"scaleX"
"scaleY"
"scale"
"alpha"
"redMultiplier"
"greenMultiplier"
"blueMultiplier"
"alphaMultiplier"
param: (string) The name of the parameter value: (number) The new value of the specified parameter
-- the following two lines do the same thing
sprite:setX(10)
sprite:set("x", 10)
-- the following two lines do the same thing
sprite:setY(10)
sprite:set("y", 10)
-- the following two lines do the same thing
sprite:setRotation(10)
sprite:set("rotation", 10)
-- the following two lines do the same thing
sprite:setScaleX(0.5)
sprite:set("scaleX", 0.5)
-- the following two lines do the same thing
sprite:setScaleY(0.5)
sprite:set("scaleY", 0.5)
-- the following two lines do the same thing
sprite:setScale(0.5)
sprite:set("scale", 0.5)
Returns the specified property of this sprite instance by its name. These names are supported:
"x"
"y"
"rotation"
"scaleX"
"scaleY"
"alpha"
"redMultiplier"
"greenMultiplier"
"blueMultiplier"
"alphaMultiplier"
param: (string) The name of the parameter
The value of the parameter
-- the following two lines do the same thing
x = sprite:getX()
x = sprite:get("x")
-- the following two lines do the same thing
y = sprite:getY()
y = sprite:get("y")
-- the following two lines do the same thing
rotation = sprite:getRotation()
rotation = sprite:get("rotation")
-- the following two lines do the same thing
scaleX = sprite:getScaleX()
scaleX = sprite:get("scaleX")
-- the following two lines do the same thing
scaleY = sprite:getScaleY()
scaleY = sprite:get("scaleY")
Returns the Sprite
object that contains this Sprite
object.
The parent sprite.
Returns the number of children of this sprite.
The number of children of this sprite.
local container1 = Sprite.new()
local container2 = Sprite.new()
local sprite1 = Sprite.new();
local sprite2 = Sprite.new();
container2:addChild(container1)
container1:addChild(sprite1)
container1:addChild(sprite2)
print(container1:getNumChildren()) --> 2
print(container2:getNumChildren()) --> 1
print(sprite1:getNumChildren()) --> 0
print(sprite2:getNumChildren()) --> 0
Returns the alpha transparency of this sprite. 0 means fully transparent and 1 means fully opaque.
The alpha of the sprite
Sets the alpha transparency of this sprite. 0 means fully transparent and 1 means fully opaque.
alpha: (number) The new alpha transparency of the sprite
Sets the red, green, blue and alpha channel multipliers. This function lets you adjust the color multipliers of a display object. This adjustment also applies to the children of this sprite instance.
redMultiplier: (number, default = 1) The red multiplier of this sprite greenMultiplier: (number, default = 1) The green multiplier of this sprite blueMultiplier: (number, default = 1) The blue multiplier of this sprite alphaMultiplier: (number, default = 1) The alpha multiplier of this sprite
Returns the red, green, blue and alpha channel multipliers.
4 values: redMultiplier, greenMultiplier, blueMultiplier and alphaMultiplier
Checks whether the given coordinates (in global coordinate system) is in bounds of the sprite.
x: (number) y: (number)
true
if the given global coordinates are in bounds of the sprite, false
otherwise.
Returns the transformation matrix of the sprite. Each invocation of this function returns a new Matrix
object.
The transformation matrix of the sprite
Sets the transformation matrix of the sprite.
matrix: (Matrix)
If the sprite has a parent, removes the sprite from the child list of its parent sprite. This function is equilavent to:
function Sprite:removeFromParent()
local parent = self:getParent()
if parent ~= nil then
parent:removeChild(self)
end
end
Sets the blend mode of the sprite. Currently supported blending modes are:
If a Sprite
object doesn’t set any blending mode, it takes the blending mode from its parent sprite.
Note: The following two lines are completely same: sprite:setBlendMode(“add”) sprite:setBlendMode(Sprite.ADD) It’s a matter of taste which one to choose.
blendMode: (String)
Clears the blending mode.
Returns a rectangle (as x, y, width and height) that encloses the sprite as it appears in another sprite’s coordinate system.
targetSprite: (Sprite) the sprite that defines the other coordinate system to transform
4 values as x, y, width and height of bounds
local x, y, width, height = sprite:getBounds(sprite) -- returns local (untransformed) bounds
local x, y, width, height = sprite:getBounds(stage) -- returns bounds as transformed to stage's coordinate system
The Stage
class represents the top of the scene tree hierarchy. The instances of Stage
is not created directly (there is not any Stage.new
function) but
there is already a global variable stage
.
This function is obsolete. Use Application:setBackgroundColor instead.
Sets the background color (or clear color) of the application. Default background color is white (1, 1, 1).
r: (number) red component of background color g: (number) green component of background color b: (number) blue component of background color
This function is obsolete. Use Application:getBackgroundColor instead.
Returns the r, g, b values of background color.
The r, g, b values of background color.
This function is obsolete. Use Application:setOrientation instead.
orientation: (string)
stage:setOrientation(Stage.PORTRAIT) -- the buttons are on the bottom
stage:setOrientation(Stage.PORTRAIT_UPSIDE_DOWN) -- the buttons are at the top
stage:setOrientation(Stage.LANDSCAPE_LEFT) -- the buttons are on the right side
stage:setOrientation(Stage.LANDSCAPE_RIGHT) -- the buttons are on the left side
This function is obsolete. Use Application:getOrientation instead.
Returns the orientation of the stage.
The orientation of the stage
TextureBase
is the base class for Texture
and TexturePack
classes. It provides a common functionaly to texture related classes.
Returns the width of the texture in pixels.
The width of the texture in pixels.
Returns the height of the texture in pixels.
The height of the texture in pixels.
The Texture
class lets you work with textures in an application. The Texture
class lets you create
a new Texture
object to load from an image file and display in scene tree.
Creates a new Texture object.
filename: (string) The name of the texture file to be loaded. filtering: (boolean, default = false) Whether or not the texture is filtered. options: (table, optional) A table that specifies optional paramaters. Currently, "transparentColor" and "wrap" fields are supported.
local texture = Texture.new("image.png", false, {transparentColor = 0xff00ff}) -- do not filter and make the color 0xff00ff transparent
local texture = Texture.new("image.png", true, {wrap = Texture.REPEAT}) -- enable filtering and repeat the texture
The TextureRegion
class specifies a texture and a rectangular region in it. It is used to define independent texture regions
within a texture atlas which is a large image, which contains many smaller sub-images.
local texture = Texture.new("atlas.png")
-- define 4 equal regions of size 100x100 from "atlas.png"
local region1 = TextureRegion.new(texture, 0, 0, 100, 100)
local region2 = TextureRegion.new(texture, 100, 0, 100, 100)
local region3 = TextureRegion.new(texture, 100, 100, 100, 100)
local region4 = TextureRegion.new(texture, 0, 100, 100, 100)
-- add these regions to scene tree
local bitmap1 = Bitmap.new(region1)
local bitmap2 = Bitmap.new(region2)
local bitmap3 = Bitmap.new(region3)
local bitmap4 = Bitmap.new(region4)
stage:addChild(bitmap1)
stage:addChild(bitmap2)
stage:addChild(bitmap3)
stage:addChild(bitmap4)
Creates a new TextureRegion object.
texture: (TextureBase) texture object
Creates a new TextureRegion object.
texture: (TextureBase) texture object x: (number) left coordinate of the region y: (number) top coordinate of the region width: (number) width of the region height: (number) height of the region
Sets the coordinates of the region.
x: (number) left coordinate of the region y: (number) top coordinate of the region width: (number) width of the region height: (number) height of the region
Returns the coordinates of the region.
The coordinates of the region as 4 values: x, y, width and height
The TexturePack
class specifies a texture pack (or texture atlas). A texture atlas is a large image which contains many smaller sub-images.
Gideros supports dynamic creation of texture atlases and pre-packed texture atlasses by using “Gideros Texture Packer” tool.
To create a texture pack dynamically (at run-time), create TexturePack
object with a table of file names of textures.
local pack = TexturePack.new({"1.png", "2.png", "3.png", "4.png")}
To create a pre-packed texture atlas, use “Gideros Texture Packer” tool:
This tool exports two files: A .txt file that specifes the positions of texture regions and a .png file of packed texture. Use these two files to create texture pack:
local pack = TexturePack.new("pack.txt", "pack.png")
Creates a new TexturePack
object. This function creates the texture pack at runtime.
textures: (table) file names of textures. padding: (number) the spacing between textures in pixels filtering: (boolean, default = false) Whether or not the texture is filtered. options: (table, optional) A table that specifies optional paramaters. Currently "transparentColor" field is supported.
Creates a new TexturePack
object. This function loads the pre-packed texture atlas created by “Gideros Texture Packer” tool.
txtfile: (string) imagefile: (string) filtering: (boolean, default = false) Whether or not the texture is filtered. options: (table, optional) A table that specifies optional paramaters. Currently "transparentColor" field is supported.
Returns the texture region of texture pack.
texturename: (string)
TextureRegion
object that specifies the region within the texture pack.
local pack = TexturePack.new({"gfx/1.png", "gfx/2.png", "gfx/3.png", "gfx/4.png"})
local region1 = pack:getTextureRegion("gfx/1.png")
local region2 = pack:getTextureRegion("gfx/2.png")
local region3 = pack:getTextureRegion("gfx/3.png")
local region4 = pack:getTextureRegion("gfx/4.png")
The Bitmap
class is used to display texture related objects in the scene tree. It is possible to create Bitmap object from TextureBase
or TextureRegion
instances.
Creates a new Bitmap
object.
texture: (TextureBase or TextureRegion)
local texture = Texture.new("image.png")
local region = TextureRegion.new(texture, 0, 0, 100, 50)
local bitmap1 = Bitmap.new(texture)
local bitmap2 = Bitmap.new(region)
stage:addChild(bitmap1)
stage:addChild(bitmap2)
Sets the anchor point of Bitmap
object.
Each Bitmap
object has an anchor point that affects the positioning of the texture displayed. By modifying the anchor point, you change the origin of the texture. For example, setting the anchor point to (0.5, 0.5) moves the center of the texture to the origin. If you set the anchor point to (1, 1) instead, the bottom-right corner of the texture will be the origin. The default value of anchor point is (0, 0) which means top-left of the texture is the origin by default.
x: (number) The x coordinate of anchor point. Usually between [0, 1]. y: (number) The y coordinate of anchor point. Usually between [0, 1].
Returns the x and y coordinates of the anchor point.
The x and y coordinates of the anchor point.
Sets the texture.
texture: (TextureBase)
Sets the texture region.
textureRegion: (TextureRegion)
FontBase
is the base class for Font
and TTFont
classes.
Returns the tight bounding rectangle of the characters in the string specified by text
.
text: (string)
4 values as x, y, width and height of bounds
Returns the width of the first size
characters of text
.
Note that this value is not equal to the 3rd return value (width) of getBounds()
.
getBounds()
returns a rectangle describing the bounds this string will cover
whereas getAdvanceX()
returns the distance to where the next string should be drawn.
text: (string) letterSpacing: (number, default = 0) size: (number, optional)
The width of the first size characters of text.
Returns the ascender of the font. The ascender of a font is the distance from the baseline to the highest position characters extend to.
The ascender of the font
Returns the distance from one base line to the next.
The distance from one base line to the next.
The ‘Font’ class is used to load fonts created by “Gideros Font Creator”.
Gideros Font Creator exports two files: A .txt file that specifes the positions of character glyph a .png file of font.
Use these two files to create Font
object as:
local font = Font.new("font.txt", "font.png")
Creates a new Font
object.
txtfile: (string) imagefile: (string) filtering: (boolean, default = false) Whether or not the font texture is filtered
The TTFont
class is used to load true type fonts.
Creates a new TTFont
object.
filename: (string) The name of the TTF file to be loaded size: (number) size of the font text: (string, optional) if specified, TTFont caches the characters of this test to speed up the rendering filtering: (boolean, default = false) Whether or not the font texture is filtered
The TextField
class is used to create display objects for text display.
local font = Font.new("myfont.txt", "myfont.png")
local textfield = TextField.new(font, "some text")
stage:addChild(textfield)
textfield:setText("some other text") -- change the text
-- to use the default font, pass nil value for the font parameter
local textfield2 = TextField.new(nil, "some other text with default font")
Creates a new TextField
object with the specified font and text. Gideros runtime includes a
default font. If you specify nil
for the font parameter while creating the TextField
object, default font is used.
font: (FontBase) The font used for displaying this `TextField` object. If nil, default font is used. text: (string, optional) The text to be displayed.
Sets the text to be displayed.
text: (string) The text to be displayed.
Returns the text displayed.
The text displayed.
Sets the color of the text in a text field in hexadecimal format.
color: (number) color of the text in hexadecimal format.
textfield:setTextColor(0xff0000) -- red
textfield:setTextColor(0x00ff00) -- green
textfield:setTextColor(0x0000ff) -- blue
The color of the text in a text field, in hexadecimal format.
Sets the letter-spacing property which is used to increase or decrease the space between characters in a text.
spacing: (number)
Returns the letter-spacing property which is used to increase or decrease the space between characters in a text.
The letter-spacing property of the text field.
The Shape
class is used create and display vector graphics.
Creates a new Shape
object.
Sets the fill style that Shape
object uses for subsequent drawings. The fill style remains in effect until you call setFillStyle()
function with different
parameters.
type
parameter can be one of the following values:
See the following example for more detailed usage of this function.
type: (string) The type of the fill. Can be one of the Shape.NONE, Shape.SOLID or Shape.TEXTURE. ...: Parameters of the fill style.
setFillStyle(Shape.NONE) -- clears the fill style
setFillStyle(Shape.SOLID, 0xff0000) -- sets the fill style as solid red color
setFillStyle(Shape.SOLID, 0xff0000, 0.5) -- sets the fill style as solid red color with 0.5 transparency
local texture = Texture.new("image.png")
setFillStyle(Shape.TEXTURE, texture) -- sets the fill style as texture with "image.png"
local matrix = Matrix.new(0.5, 0, 0, 0.5, 0, 0)
setFillStyle(Shape.TEXTURE, texture, matrix) -- sets the fill style as texture with "image.png" with a transformation matrix
Sets the line style that Shape
object uses for subsequent drawings. The line style remains in effect until you call setLineStyle()
function with different
parameters.
width: (number) The width of the line. If this parameter is 0, line is not drawn. color: (number, default = 0x000000) A hexadecimal color value of the line. For example, red is 0xFF0000, blue is 0x0000FF, and so on. alpha: (number, default = 1) The alpha value of the color of the line.
Resets the current path.
winding: (string, default = Shape.EVEN_ODD) Specifies the winding rule. It can be either Shape.EVEN_ODD or Shape.NON_ZERO.
Creates a new subpath with the given point.
x: (number) x coordinate of the point. y: (number) y coordinate of the point.
Adds the given point to the current subpath, connected to the previous one by a straight line.
x: (number) x coordinate of the point. y: (number) y coordinate of the point.
Ends the current path and draws the geometry by using the specified line and fill styles.
Marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.
Clears the graphics that were drawn to this Shape
object, and resets fill and line style settings.
The TileMap
class is used to work with tile maps easily and efficiently.
Creates a new TileMap
instance.
width: (number) The width of the map in tiles height: (number) The height of the map in tiles texture: (TextureBase) The texture used in rendering tile map tilewidth: (number) The width of a tile in pixels tileheight: (number) The height of a tile in pixels spacingx: (number, default = 0) The x-spacing in pixels between the tiles in this tileset spacingy: (number, default = 0) The y-spacing in pixels between the tiles in this tileset marginx: (number, default = 0) The x-margin from the top-left of the texture marginy: (number, default = 0) The y-margin from the top-left of the texture displaywidth: (number, default = tilewidth) The display width of a tile in pixels displayheight: (number, default = tileheight) The display height of a tile in pixels
Returns the index of the tile. The tile indices are starting from 1.
x: (number) The x-position of tile y: (number) The y-position of tile
If the tile is empty, returns nil
, otherwise returns x,y index and flip flag of the tile.
Sets the index of the tile. The tile indices are starting from 1.
x: (number) The x-position of tile y: (number) The y-position of tile tx: (number) The x-index of the tile ty: (number) The y-index of the tile flip: (number, default = 0) flip flag of tile. Can be combination of TileMap.FLIP_HORIZONTAL, TileMap.FLIP_VERTICAL and TileMap.FLIP_DIAGONAL
Set an empty tile at given indices. The tile indices are starting from 1.
x: (number) The x-position of tile y: (number) The y-position of tile
Shifts the tile map. The arguments are in tiles, not in pixels. By shifting the tile map one by one as needed, you can create dynamic tile maps.
dx: (number) The x amount of shift in tiles dy: (number) The y amount of shift in tiles
tilemap:shift(-1, 0) -- shifts the tile map to the left
tilemap:shift(1, 0) -- shifts the tile map to the right
tilemap:shift(0, -1) -- shifts the tile map to the up
tilemap:shift(0, 1) -- shifts the tile map to the down
The MovieClip
class inherits from the following classes: Sprite
> EventDispatcher
.
The MovieClip
class is used create static timedlined animations. The timeline parameters are given as an array.
Each array element specifies one timeline element and consists of the starting frame, ending frame, sprite and
optional tweening parameters. Frame numbers start from 1.
When a MovieClip
object finishes it playing (by reaching its final frame or a frame with stop action),
it dispatches an Event.COMPLETE
event.
The following properties can be tweened:
x
y
rotation
scale
scaleX
scaleY
alpha
The following easing functions can be used:
"inBack"
"outBack"
"inOutBack"
"inBounce"
"outBounce"
"inOutBounce"
"inCircular"
"outCircular"
"inOutCircular"
"inCubic"
"outCubic"
"inOutCubic"
"inElastic"
"outElastic"
"inOutElastic"
"inExponential"
"outExponential"
"inOutExponential"
"linear"
"inQuadratic"
"outQuadratic"
"inOutQuadratic"
"inQuartic"
"outQuartic"
"inOutQuartic"
"inQuintic"
"outQuintic"
"inOutQuintic"
"inSine"
"outSine"
"inOutSine"
Following examples demonstrates the possible uses of MovieClip class.
-- construct a 100 frame animation where x coordinate of sprite tweens from 0 to 200 linearly
local mc = MovieClip.new{
{1, 100, sprite, {x = {0, 200, "linear"}}}
}
-- construct a 100 frame animation where x coordinate of sprite is 50 (constant) and
-- y coordinate of sprite tweens from 50 to 150 by using inBounce function
local mc = MovieClip.new{
{1, 100, sprite, {x = 50, y = {50, 150, "inBounce"}}}
}
-- construct a 200 frame animation where sprite1 and sprite2 tweens differently
-- here sprite1 is visible between frames [1, 150]
-- and sprite2 is visible between frames [100, 200]
local mc = MovieClip.new{
{1, 100, sprite1, {x = {0, 200, "linear"}}},
{50, 150, sprite1, {y = {0, 100, "linear"}}, {alpha = {0, 1, "easeOut"}}},
{100, 200, sprite2, {x = {0, 200, "linear"}}},
}
-- construct a looping 6 frame animation where each frame is a different sprite
local mc = MovieClip.new{
{1, 1, frame1},
{2, 2, frame2},
{3, 3, frame3},
{4, 4, frame4},
{5, 5, frame5},
{6, 6, frame6},
}
mc:setGotoAction(6, 1) -- if the animation reaches frame 6 then go to frame 1
-- construct a looping 6 frame animation playing 5 times slower than the previous example
local mc = MovieClip.new{
{1, 5, frame1},
{5, 10, frame2},
{11, 15, frame3},
{16, 20, frame4},
{21, 25, frame5},
{26, 30, frame6},
}
mc:setGotoAction(30, 1) -- if the animation reaches frame 30 then go to frame 1
Creates a new MovieClip
object. After constructing the MovieClip object, it starts playing. You don’t need to
call MovieClip:play.
timeline: (table) array of timeline elements
Starts playing the movie clip.
Stops playing the movie clip.
Goes to the specified frame and starts playing.
frame: (int) the frame number
Goes to the specified frame and stops.
frame: (int) the frame number
Sets a goto action to the specified frame. When the movie clip reaches a frame with goto action, it jumps to the destination frame and continues to play. This function is usually used to create looping animations.
frame: (int) the frame number destframe: (int) the destination frame number
Sets a stop action to the specified frame. When the movie clip reaches a frame with stop action, it stops playing. This function is usually used to divide the animation into independent parts.
frame: (int) the frame number
Clears the action (goto or stop) at the specified frame.
frame: (int) the frame number
Mesh class is used to create and display custom constructed set of triangles (triangle meshes). It basically consists of 4 arrays: vertex, index, color (optional), textureCoordinate (optional) and a texture (optional) and it provides more than one way to set/modify these arrays.
Note 1: Mesh class doesn’t do bounds check. If an element at index array points to an non-existent vertex, the application may crash.
Note 2: If color array is set, then setAlpha
and setColorTransform
functions doesn’t effect the Mesh sprite.
Creates a new Mesh
object.
Sets a vertex at vertex array. Indices are start from 1. If the vertex array is not large enough, it’s expanded automatically.
i: (number) index x: (number) x coordinate y: (number) y coordinate
-- set the first 3 vertex positions as (100, 100), (150, 100) and (100, 150).
mesh:setVertex(1, 100, 100)
mesh:setVertex(2, 150, 100)
mesh:setVertex(3, 100, 150)
Sets a index at index array. Indices are start from 1. If the index array is not large enough, it’s expanded automatically.
i: (number) index index: (number) index
-- set the first 3 indices as 10, 11 and 12.
mesh:setIndex(1, 10)
mesh:setIndex(2, 11)
mesh:setIndex(3, 12)
Sets a color at color array. Indices are start from 1. If the color array is not large enough, it’s expanded automatically.
i: (number) index color: (number) color in hexedecial value alpha: (number, default=1.0) alpha value
-- set the first 3 colors as (0xff0000, 0.5), (0x00ff00, 0.7) and (0x0000ff, 1.0).
mesh:setColor(1, 0xff0000, 0.5) -- red with 0.5 alpha
mesh:setColor(2, 0x00ff00, 0.7) -- green with 0.7 alpha
mesh:setColor(3, 0x0000ff) -- blue with 1.0 alpha
Sets a texture coordinate at texture coordinate array. Indices are start from 1. If the texture coordinate array is not large enough, it’s expanded automatically.
i: (number) index u: (number) u coordinate v: (number) v coordinate
-- set the first 3 texture coordinates as (0, 0), (100, 0) and (0, 100).
mesh:setTextureCoordinate(1, 0, 0)
mesh:setTextureCoordinate(2, 100, 0)
mesh:setTextureCoordinate(3, 0, 100)
Sets zero or more vertices at vertex array with a single function call. It accepts multiple values or a Lua array.
vertices:
-- set 3 vertices with seperate function calls
mesh:setVertex(1, 100, 100)
mesh:setVertex(2, 150, 100)
mesh:setVertex(3, 100, 150)
-- set 3 vertices with one function call
mesh:setVertices(1, 100, 100, 2, 150, 100, 3, 100, 150)
-- same as above
mesh:setVertices{1, 100, 100, 2, 150, 100, 3, 100, 150}
-- these two functions do nothing
mesh:setVertices()
mesh:setVertices{}
Sets zero or more indices at index array with a single function call. It accepts multiple values or a Lua array.
indices:
-- set 3 indices with seperate function calls
mesh:setIndex(1, 10)
mesh:setIndex(2, 11)
mesh:setIndex(3, 12)
-- set 3 indices with one function call
mesh:setIndices(1, 10, 2, 11, 3, 12)
-- same as above
mesh:setIndices{1, 10, 2, 11, 3, 12}
-- these two functions do nothing
mesh:setIndices()
mesh:setIndices{}
Sets zero or more colors at color array with a single function call. It accepts multiple values or a Lua array.
colors:
-- set 3 colors with seperate function calls
mesh:setColor(1, 0xff0000, 0.5)
mesh:setColor(2, 0x00ff00, 0.7)
mesh:setColor(3, 0x0000ff)
-- set 3 colors with one function call
mesh:setColors(1, 0xff0000, 0.5, 2, 0x00ff00, 0.7, 3, 0x0000ff, 1.0)
-- same as above
mesh:setColors{1, 0xff0000, 0.5, 2, 0x00ff00, 0.7, 3, 0x0000ff, 1.0}
-- these two functions do nothing
mesh:setColors()
mesh:setColors{}
textureCoordinates:
-- set 3 texture coordinates with seperate function calls
mesh:setTextureCoordinate(1, 0, 0)
mesh:setTextureCoordinate(2, 100, 0)
mesh:setTextureCoordinate(3, 0, 100)
-- set 3 texture coordinates with one function call
mesh:setTextureCoordinates(1, 0, 0, 2, 100, 0, 3, 0, 100)
-- same as above
mesh:setTextureCoordinates{1, 0, 0, 2, 100, 0, 3, 0, 100}
-- these two functions do nothing
mesh:setTextureCoordinates()
mesh:setTextureCoordinates{}
Assigns new content to the vertex array, dropping all the elements contained in the vertex array before the call and replacing them by those specified by the parameters. It accepts multiple values or a Lua array.
vertices:
-- set the vertex array as (100, 100), (150, 100) and (100, 150)
mesh:setVertexArray(100, 100, 150, 100, 100, 150)
-- same as above
mesh:setVertexArray{100, 100, 150, 100, 100, 150}
Assigns new content to the index array, dropping all the elements contained in the index array before the call and replacing them by those specified by the parameters. It accepts multiple values or a Lua array.
indices:
-- set the index array as 10, 11 and 12.
mesh:setIndexArray(10, 11, 12)
-- same as above
mesh:setIndexArray{10, 11, 12}
Assigns new content to the color array, dropping all the elements contained in the color array before the call and replacing them by those specified by the parameters. It accepts multiple values or a Lua array.
colors:
-- set the color array as (0xff0000, 0.5), (0x00ff00, 0.7) and (0x0000ff, 1.0).
mesh:setColorArray(0xff0000, 0.5, 0x00ff00, 0.7, 0x0000ff, 1.0)
-- same as above
mesh:setColorArray{0xff0000, 0.5, 0x00ff00, 0.7, 0x0000ff, 1.0}
Assigns new content to the texture coordinate array, dropping all the elements contained in the texture coordinate array before the call and replacing them by those specified by the parameters. It accepts multiple values or a Lua array.
textureCoordinates:
-- set the color array as (0, 0), (100, 0) and (0, 100)
mesh:setTextureCoordinateArray(0, 0, 100, 0, 0, 100)
-- same as above
mesh:setTextureCoordinateArray{0, 0, 100, 0, 0, 100}
Resizes the vertex array to contain size
elements.
If size
is smaller than the current vertex array size, the content is reduced to its first size
elements, the rest being dropped.
If size
is greater than the current vertex array size, the content is expanded by inserting at the end as many copies of 0s as needed to reach a size of size
elements.
size: (number) new vertex array size
Resizes the index array to contain size
elements.
If size
is smaller than the current index array size, the content is reduced to its first size
elements, the rest being dropped.
If size
is greater than the current index array size, the content is expanded by inserting at the end as many copies of 0s as needed to reach a size of size
elements.
size: (number) new index array size
Resizes the color array to contain size
elements.
If size
is smaller than the current color array size, the content is reduced to its first size
elements, the rest being dropped.
If size
is greater than the current color array size, the content is expanded by inserting at the end as many copies of 0s as needed to reach a size of size
elements.
size: (number) new color array size
Resizes the texture coordinate array to contain size
elements.
If size
is smaller than the current texture coordinate array size, the content is reduced to its first size
elements, the rest being dropped.
If size
is greater than the current texture coordinate array size, the content is expanded by inserting at the end as many copies of 0s as needed to reach a size of size
elements.
size: (number) new texture coordinate array size
Clears the vertex array.
Clears the index array.
Clears the color array.
Clears the texture coordinate array.
Sets the texture.
texture: (TextureBase)
Clears the texture.
Application
class contains the common functions that’s
available to the current application. There is
a global variable application
of type Application
to access these functions.
Opens the given URL (Universal Resource Locator) in the appropriate application. URL can be one of the http:
, https:
, tel:
, or mailto:
schemes.
The following example opens a web page in the browser: application:openUrl(“http://www.giderosmobile.com”)
If mailto:
scheme is specified, the user’s e-mail client will be used to open a composer window containing the options specified in the URL.
For example, the following URL contains a recipient (user@foo.com), a subject (Test), and a message body (Just a test):
application:openUrl(“mailto:user@foo.com?subject=Test&body=Just a test”)
Or to call a number: application:openUrl(“tel:555-123-4567”)
This function is obsolete. Use Accelerometer class instead.
Returns the x, y, z coordinates of the accelerometer.
Returns the logical width of the application that is specified at the project properties.
The logical width of the application
Returns the logical height of the application that is specified at the project properties.
The logical height of the application
Returns the physical width of the device in pixels. For example, for iPhone 3GS this function returns 320 and for iPhone 4 (with retina display enabled) this function returns 640.
The physical width of the device in pixels
Returns the physical height of the device in pixels. For example, for iPhone 3GS this function returns 480 and for iPhone 4 (with retina display enabled) this function returns 960.
The physical height of the device in pixels
Vibrates the device. If the device doesn’t support vibration, this function has no effect.
Returns the device locale. The locale string is a combination of ISO 639-1 and ISO 3166-1. For example, en_US, ja_JP.
The device locale
Returns the user language in ISO 639-1 format.
The the user language
Controls the screen dimming and device sleeping of the device. When the application has no touches as user input for some period,
the system puts the device into a sleep state where the screen dims. However some applications have no input and controlled
by accelerometer or gyroscope only. For these kind applications, the screen should be kept awake by calling this function
with parameter true
.
Note: This function has no effect on desktop.
keepAwake: (boolean) if true, screen is kept awake.
application:setKeepAwake(true) -- disable screen dimming and device sleeping
application:setKeepAwake(false) -- enable screen dimming and device sleeping
Returns the translation of automatic screen scaling on the x-axis.
The translation of automatic screen scaling on the x-axis.
Returns the translation of automatic screen scaling on the y-axis.
The translation of automatic screen scaling on the y-axis.
Returns the scaling of automatic screen scaling on the x-axis.
The scaling of automatic screen scaling on the x-axis.
Returns the scaling of automatic screen scaling on the y-axis.
The scaling of automatic screen scaling on the y-axis.
Returns information about device.
Information about device
If the orientation is portrait, this function returns logical width. If the orientation is landscape, this function returns logical height.
Logical width or logical height depending on orientation.
If the orientation is portrait, this function returns logical height. If the orientation is landscape, this function returns logical width.
Logical width or logical height depending on orientation.
Sets the background color (or clear color) of the application in hexadecimal format. Default background color is white (0xffffff).
color: (number) background color in hexadecimal format
Returns the background color (or clear color) of the application in hexadecimal format.
The background color in hexadecimal format.
Sets the orientation of the application. Accepted values are:
orientation: (string)
application:setOrientation(Application.PORTRAIT) -- the buttons are on the bottom
application:setOrientation(Application.PORTRAIT_UPSIDE_DOWN) -- the buttons are at the top
application:setOrientation(Application.LANDSCAPE_LEFT) -- the buttons are on the right side
application:setOrientation(Application.LANDSCAPE_RIGHT) -- the buttons are on the left side
Returns the orientation of the application.
The orientation of the application
Sets the automatic scale mode of the application. Accepted values are:
scaleMode: (string)
Returns the automatic scale mode of the application.
The automatic scale mode of the application
Sets the logical dimensions of the application.
width: (number) logical width height: (number) logical height
Sets the frame rate of the application. Accepted values are 30
and 60
.
fps: (number) the new frame rate of the application
Returns the frame rate of the application.
The frame rate of the application.
Terminates the application. Although this function is available to all platforms, it should be used on Android only.
Returns the API version.
The API version.
Returns the texture memory usage (in Kbytes).
The texture memory usage (in Kbytes).
Returns the screen density in pixels per inch. If screen density information is not available, returns nil
.
If available returns the screen density in pixels per inch, otherwise returns ‘nil’.
Returns precise time in seconds relative to some arbitrary point.
Precise time in seconds relative to some arbitrary point
The Sound
class lets you load and play WAV or MP3 sound files.
Control of the playing sound is performed through the SoundChannel
object.
local sound = Sound.new("music.mp3")
local channel = sound:play()
-- after some time --
channel:stop()
Creates a new Sound
object.
filename: (string) The name of the sound file to be loaded.
Creates a new SoundChannel
object to play the sound. By using the retured SoundChannel
object,
you can stop the sound and monitor the position.
startTime: (number, default = 0) The initial position in milliseconds at which playback should start. looping: (boolean, default = false) paused: (boolean, default = false)
A SoundChannel
object, which you use to control the sound. This function returns nil
if you run out of available sound channels.
Returns the duration of the sound in miliseconds.
The duration of the sound in miliseconds.
The SoundChannel
class is used to control and monitor a playing sound.
Event.COMPLETE
event is dispatched.Stops the sound playing in the channel.
Sets the current playback position in miliseconds.
position: (number) position of the channel to set in miliseconds
If the sound is playing, getPosition
returns the position of the current playback, measured in miliseconds from the start of the sound.
If the sound is not playing (paused or stopped), getPosition
returns the last point that was played.
The position of the sound in miliseconds.
Sets the volume of the sound channel.
volume: (number) The new volume of the sound channel. Valid range of this parameter is between 0.0 and 1.0, where 1.0 is the maximum volume value.
Returns the current volume of the sound channel.
The current volume of the sound channel.
Sets the pitch of the sound channel. You cannot set the pitch of a background music.
pitch: (number) The new pitch of the sound channel.
Returns the current pitch of the sound channel.
The current pitch of the sound channel.
Sets the paused state of the channel.
paused: (boolean) paused state to set
Returns the paused state of the channel.
true
if the channel is paused, false
otherwise.
Sets the looping state of the channel.
looping: (boolean) looping state to set
Returns the looping state of the channel.
true
if the channel is looping, false
otherwise.
Returns the playing state for the sound channel.
true
if the channel is currently playing a sound, false
otherwise.
The UrlLoader
class is used to download data from an URL. It can be used
to download (and optionally save) text files, XML files, JSON files, image files or binary files, etc.
Downloaded data is delivered at event.data
field of Event.COMPLETE
event as string. Lua is eight-bit clean and so strings
may contain characters with any numeric value, including embedded zeros. That means that you can store
any binary data into a string.
The UrlLoader
class dispatches the events Event.COMPLETE
, Event.PROGRESS
and Event.ERROR
.
This event is dispatched when loading is complete.
This event is dispatched as the notification of how far the download has progressed.
This event is dispatched when UrlLoader
fails and terminates the download.
UrlLoader supports GET, POST, PUT and DELETE methods. These are defined by these string constants:
The example below shows downloading an image file from an URL, saving it to the documents folder and displaying it on the stage. This example also shows downloading progress and handling errors.
local loader = UrlLoader.new("http://example.com/image.png")
local function onComplete(event)
local out = io.open("|D|image.png", "wb")
out:write(event.data)
out:close()
local b = Bitmap.new(Texture.new("|D|image.png"))
stage:addChild(b)
end
local function onError()
print("error")
end
local function onProgress(event)
print("progress: " .. event.bytesLoaded .. " of " .. event.bytesTotal)
end
loader:addEventListener(Event.COMPLETE, onComplete)
loader:addEventListener(Event.ERROR, onError)
loader:addEventListener(Event.PROGRESS, onProgress)
Creates a new UrlLoader
object.
url
parameter specifies the URL to download. This parameter is optional and if specified loading starts immediately.
method
parameter specifies the HTTP request method. It can be one of the values of UrlLoader.GET
, UrlLoader.POST
, UrlLoader.PUT
or UrlLoader.DELETE
.
The default HTTP method is UrlLoader.GET
.
body
parameter specifies the HTTP body data. This parameter is used only when the HTTP method is UrlLoader.POST
or or UrlLoader.PUT
.
After loading is finished, loaded data is stored at event.data
field of Event.COMPLETE
event as string.
url: (string, optional) URL to download. This parameter is optional and if specified loading starts immediately. method: (string, default = "get") HTTP request method. headers: (table, optional) HTTP headers. body: (string, optional) HTTP body data. This data is sent as the message body of a request.
local url = "http://www.[yourDomain].com/application.php?userid=gideros&login=guest"
local loader1 = UrlLoader.new(url)
local loader2 = UrlLoader.new(url, UrlLoader.GET) -- same as the previous line
local loader3 = UrlLoader.new(url, UrlLoader.POST, "my post data")
local loader4 = UrlLoader.new(url, UrlLoader.PUT, "my put data")
local loader5 = UrlLoader.new(url, UrlLoader.DELETE)
local headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
["User-Agent"] = "Gideros Browser",
}
local loader6 = UrlLoader.new(url, UrlLoader.PUT, headers, "key=value")
Loads data from the specified URL. If there is any load operation in progress, it is terminated and new progress starts.
Please refer to UrlLoader.new for more detailed description of url
, method
and body
parameters.
url: (string, optional) URL to download. This parameter is optional and if specified loading starts immediately. method: (string, default = "get") HTTP request method. headers: (table, optional) HTTP headers. body: (string, optional) HTTP body data. This data is sent as the message body of a request.
Terminates the current loading operation.
The Timer
class is used to execute a code at specified intervals. The listener functions are registered
through Event.TIMER
and Event.TIMER_COMPLETE
events.
Creates a new Timer
object with the specified delay and repeatCount states.
delay: The time interval between timer events in milliseconds. repeatCount: (default = 0) The number of repetitions. A value of 0 runs the timer infinitely. If nonzero, the timer runs the specified number of times and then stops.
Starts the timer.
Stops the timer. This function doesn’t change the currentCount
property.
Stops the timer and sets the currentCount
property to 0.
Returns the time interval between timer events in milliseconds.
The time interval between timer events in milliseconds.
Returns the current trigger count of the timer. It starts with 0 and if it reaches repeatCount
value, timer stops.
The current trigger count.
Returns the number of repetitions the timer will make. A value of 0 means the timer runs infinitely. If nonzero, the timer runs the specified number of times and then stops.
The number of repetitions.
Returns the current running status of timer.
true
if the timer is running, false
otherwise.
Sets the time interval between timer events in milliseconds.
delay: (number) The time interval between timer events in milliseconds.
Sets the number of repetitions the timer will make. A value of 0 means the timer runs infinitely. If nonzero, the timer runs the specified number of times and then stops.
repeatCount: (number) the number of repetitions the timer will make
Provides a simple way to call a function after a set amount of time. This function returns the
Timer
object created inside.
delay: (number) Delay in miliseconds before the function is called func: (function) Function to call data: (optional) An optional data parameter that is passed as a first argument to the function
The Timer
object
This function is obsolete. Use Timer.pauseAll instead.
Pause all timers. Suitable for temporarily pausing all timers when application is paused.
This function is obsolete. Use Timer.resumeAll instead.
Resume all timers.
Pause all timers. Suitable for temporarily pausing all timers when application is paused.
Resume all timers.
Stop all timers.
The Matrix class specifies 2D transformation from one coordinate space to another. These transformations include translation, rotation, scaling and skewing.
A 2D transformation matrix is a 3 x 3 matrix in homogenous coordinate system:
You can get and set the values of all six of the properties in a
Matrix object: m11
, m12
, m21
, m22
, tx
, and ty
.
Creates a new Matrix object with the specified parameters.
m11: (number, default = 1) m12: (number, default = 0) m21: (number, default = 0) m22: (number, default = 1) tx: (number, default = 0) ty: (number, default = 0)
New Matrix
object.
Returns the value of the m11
component for this Matrix
instance.
The current m11
parameter.
Returns the value of the m12
component for this Matrix
instance.
The current m12
parameter.
Returns the value of the m21
component for this Matrix
instance.
The current m21
parameter.
Returns the value of the m22
component for this Matrix
instance.
The current m22
parameter.
Returns the value of the tx
component for this Matrix
instance.
The current tx
parameter.
Returns the value of the ty
component for this Matrix
instance.
The current ty
parameter.
Sets the value of the m11
component for this Matrix
instance.
m11: (number)
Sets the value of the m12
component for this Matrix
instance.
m12: (number)
Sets the value of the m21
component for this Matrix
instance.
m21: (number)
Sets the value of the m22
component for this Matrix
instance.
m22: (number)
Sets the value of the tx
component for this Matrix
instance.
tx: (number)
Sets the value of the ty
component for this Matrix
instance.
ty: (number)
Returns the elements of the matrix.
m11, m12, m21, m22, tx, ty
Sets all 6 elements of the matrix.
m11: (number, default = 1) m12: (number, default = 0) m21: (number, default = 0) m22: (number, default = 1) tx: (number, default = 0) ty: (number, default = 0)
To load the Box2D library, call require "box2d"
. After loading Box2D library, b2
table stores all
classes and functions related to Box2D physics library.
Box2D is tuned for MKS (meters-kilogram-second) units and the size of moving objects should roughly between 0.1 and 10 meters. If you directly use the pixels as your units, unfortunately this will lead to a poor simulation and possibly weird behavior.
Gideros uses an internal scale system to convert between meters and pixels. By default, the value of this scale is 30
which means 1 meter = 30 pixels. This is a global value and effects all the physics system. Therefore, it is recommended to set this
value once before any physical objects are instantiated (e.g. right after calling require "box2d"
)
scale: (number) - the global pixels to meters scale
Returns the global pixels to meters scale (Please refer to b2.setScale function for more information about pixels to meters scaling).
The global pixels to meters scale
Creates and returns a revolute joint definition table with the bodies, local anchors, and reference angle using a world anchor point. (Please refer to b2.World:createJoint function for more information about all the information needed to create a revolute joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body anchorx: (number) the x coordinate of the world anchor point anchory: (number) the y coordinate of the world anchor point
A new revolute joint definition table
b2.World:createJoint
b2.RevoluteJoint
local jointdef = b2.createRevoluteJointDef(bodyA, bodyB, anchorx, anchory)
local joint = b2.World:createJoint(jointdef)
Creates and returns a prismatic joint definition table with the bodies, anchors, axis, and reference angle using the world anchor and world axis. (Please refer to b2.World:createJoint function for more information about all the information needed to create a prismatic joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body anchorx: (number) the x coordinate of the world anchor point anchory: (number) the y coordinate of the world anchor point axisx: (number) the x coordinate of the world axis axisy: (number) the y coordinate of the world axis
A new prismatic joint definition table
b2.World:createJoint
b2.PrismaticJoint
Creates and returns a distance joint definition table with the bodies, anchors, and length using the world anchors. (Please refer to b2.World:createJoint function for more information about all the information needed to create a distance joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body anchorAx: (number) the x coordinate of the world anchor point of bodyA anchorAy: (number) the y coordinate of the world anchor point of bodyA anchorBx: (number) the x coordinate of the world anchor point of bodyB anchorBy: (number) the y coordinate of the world anchor point of bodyB
A new distance joint definition table
b2.World:createJoint
b2.DistanceJoint
Creates and returns a pulley joint definition table with the bodies, anchors, lengths, max lengths, and ratio using the world anchors. (Please refer to b2.World:createJoint function for more information about all the information needed to create a pulley joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body groundAnchorAx: (number) the x coordinate of the first ground anchor in world coordinates. This point never moves. groundAnchorAy: (number) the y coordinate of the first ground anchor in world coordinates. This point never moves. groundAnchorBx: (number) the x coordinate of the second ground anchor in world coordinates. This point never moves. groundAnchorBy: (number) the y coordinate of the second ground anchor in world coordinates. This point never moves. anchorAx: (number) the x coordinate of the world anchor point of bodyA anchorAy: (number) the y coordinate of the world anchor point of bodyA anchorBx: (number) the x coordinate of the world anchor point of bodyB anchorBy: (number) the y coordinate of the world anchor point of bodyB ratio: (number) the pulley ratio, used to simulate a block-and-tackle
A new pulley joint definition table
b2.World:createJoint
b2.PulleyJoint
Creates and returns a mouse joint definition table with the bodies, world target point, maxForce and optional frequencyHz and dampingRatio. (Please refer to b2.World:createJoint function for more information about all the information needed to create a mouse joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body targetx: (number) the x coordinate of the world target point targety: (number) the y coordinate of the world target point maxForce: (number) the maximum constraint force that can be exerted to move the candidate body frequencyHz: (number, default = 5) the response speed dampingRatio: (number, default = 0.7) the damping ratio. 0 = no damping, 1 = critical damping
A new mouse joint definition table
b2.World:createJoint
b2.MouseJoint
Creates and returns a gear joint definition table. (Please refer to b2.World:createJoint function for more information about all the information needed to create a gear joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body joint1: (b2.Joint) the first revolute/prismatic joint attached to the gear joint joint2: (b2.Joint) the second revolute/prismatic joint attached to the gear joint ratio: (number, default = 1) the gear ratio
A new gear joint definition table
b2.World:createJoint
b2.GearJoint
Creates and returns a wheel joint definition table. (Please refer to b2.World:createJoint function for more information about all the information needed to create a wheel joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body anchorx: (number) the x coordinate of the world anchor point anchory: (number) the y coordinate of the world anchor point axisx: (number) the x coordinate of the world translation axis in bodyA axisy: (number) the y coordinate of the world translation axis in bodyA
A new wheel joint definition table
b2.World:createJoint
b2.WheelJoint
Creates and returns a weld joint definition table with the bodies, anchors, and reference angle using a world anchor point. (Please refer to b2.World:createJoint function for more information about all the information needed to create a weld joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body anchorAx: (number) the x coordinate of the world anchor point of bodyA anchorAy: (number) the y coordinate of the world anchor point of bodyA anchorBx: (number) the x coordinate of the world anchor point of bodyB anchorBy: (number) the y coordinate of the world anchor point of bodyB
A new weld joint definition table
b2.World:createJoint
b2.WeldJoint
Creates and returns a friction joint definition table with the bodies and local anchors using a world anchor point. (Please refer to b2.World:createJoint function for more information about all the information needed to create a friction joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body anchorx: (number) the x coordinate of the world anchor point anchory: (number) the y coordinate of the world anchor point
A new friction joint definition table
b2.World:createJoint
b2.FrictionJoint
Creates and returns a rope joint definition table with the bodies and local anchors using a world anchor point. (Please refer to b2.World:createJoint function for more information about all the information needed to create a rope joint).
bodyA: (b2.Body) the first attached body bodyB: (b2.Body) the second attached body anchorAx: (number) the x coordinate of the world anchor point of bodyA anchorAy: (number) the y coordinate of the world anchor point of bodyA anchorBx: (number) the x coordinate of the world anchor point of bodyB anchorBy: (number) the y coordinate of the world anchor point of bodyB maxLength: (number) the maximum length of the rope
A new rope joint definition table
b2.World:createJoint
b2.RopeJoint
The b2.World
class inherits from the following class: EventDispatcher
.
The b2.World
class manages all physics entities and dynamic simulation. It is possible to create and manage more than one b2.World
instance.
Creates a new b2.World
object. You can create more then one b2.World
object to manage independent worlds.
gravityx: (number) the x component the gravity gravityy: (number) the y component the gravity doSleep: (boolean, default = true) improve performance by not simulating inactive bodies
A new b2.World
object.
Creates a rigid body given a definition. The body definition is given as an ordinary table. The fields of the body definition table are:
b2.STATIC_BODY
, b2.KINEMATIC_BODY
, or b2.DYNAMIC_BODY
. Note: if a dynamic body would have zero mass, the mass is set to one.The unset fields gets default values.
Warning: This function is locked during callbacks.
bodyDef: (table)
The created b2.Body
instance.
local body = world:createBody{
type = b2.STATIC_BODY,
position = {x=0, y=0.5},
angle = math.pi/4,
linearVelocity = {x=0.1, y=0.2},
}
Destroys a rigid body. This function is locked during callbacks.
Warning:
body: (b2.Body) body to be destroyed
Take a time step. This performs collision detection, integration, and constraint solution.
timeStep: (number) the amount of time to simulate, this should not vary velocityIterations: (number) for the velocity constraint solver positionIterations: (number) for the position constraint solver
Call this after you are done with time steps to clear the forces. You normally call this after each call to b2.World:step
,
unless you are performing sub-steps. By default, forces will be automatically cleared, so you don’t need to call this function.
Sets the gravity vector.
gravityx: (number) the x component the gravity gravityy: (number) the y component the gravity
Returns the gravity vector.
x and y component of gravity vector.
Query the world for all fixtures that potentially overlap the provided AABB.
lowerx: (number) the lower x coordinate of the query box lowery: (number) the lower y coordinate of the query box upperx: (number) the upper x coordinate of the query box uppery: (number) the upper y coordinate of the query box
Array of fixtures that potentially overlaps the provided AABB
Ray-cast the world for all fixtures in the path of the ray. Your callback controls whether you get the closest point, any point, or n-points. The ray-cast ignores shapes that contain the starting point.
Listener function is called for each fixture found in the query and accepts 6 parameters (7 if data parameter is provided):
You control how the ray cast proceeds by returning a number:
x1: (number) the x coordinate of the ray starting point y1: (number) the y coordinate of the ray starting point x2: (number) the x coordinate of the ray ending point y2: (number) the y coordinate of the ray ending point listener: (function) the listener function that processes the results data: (optional) an optional data parameter that is passed as a first argument to the listener function
Creates a joint given a definition. All 10 types of joints is created by using this function:
Revolute joint definition. This requires defining an anchor point where the bodies are joined. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body’s origin rather than the center of mass because:
and recompute the mass, the joints will be broken.
Also, you can use b2.createRevoluteJointDef function to create a revolute joint definiton table easier.
Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game.
Also, you can use b2.createPrismaticJointDef function to create a prismatic joint definiton table easier.
Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when saving and loading a game.
Also, you can use b2.createDistanceJointDef function to create a distance joint definiton table easier.
Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio.
Also, you can use b2.createPulleyJointDef function to create a pulley joint definiton table easier.
Mouse joint definition. This requires a world target point, tuning parameters, and the time step.
Also, you can use b2.createMouseJointDef function to create a mouse joint definiton table easier.
Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). The provided joints must attach a dynamic body to a static body.
Also, you can use b2.createGearJointDef function to create a gear joint definiton table easier.
Wheel joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game.
Also, you can use b2.createWheelJointDef function to create a wheel joint definiton table easier.
Weld joint definition. You need to specify local anchor points where they are attached and the relative body angle. The position of the anchor points is important for computing the reaction torque.
Also, you can use b2.createWeldJointDef function to create a weld joint definiton table easier.
Friction joint definition.
Rope joint definition. This requires two body anchor points and a maximum length.
Also, you can use b2.createRopeJointDef function to create a rope joint definiton table easier.
jointDef: (table)
The created joint instance.
Destroy a joint. This may cause the connected bodies to begin colliding.
Warning: This function is locked during callbacks.
joint: (b2.Joint) joint to be destroyed
Registers a b2.DebugDraw instance for debug drawing.
A rigid body. These are created via b2.World:createBody
.
Returns the world body origin position.
x and y coordinates of the position
Sets the world body origin position.
x: (number) x coordinate of the position y: (number) y coordinate of the position
Sets the current world rotation angle in radians.
angle: (number) world rotation angle in radians
Returns the current world rotation angle in radians.
Current body angle in radians
Returns the linear velocity of the center of mass.
x and y coordinates of the linear velocity
Sets the linear velocity of the center of mass.
x: (number) x coordinate of the linear velocity y: (number) y coordinate of the linear velocity
Sets the angular velocity.
omega: (number) the new angular velocity in radians/second
Returns the angular velocity.
Angular velocity in radians/second
Creates a fixture and attach it to this body. If the density is non-zero, this function automatically updates the mass of the body. Contacts are not created until the next time step. The fixture definition is given as a ordinary table. The fields of the fixture definition table are:
b2.Fixture:setFilterData
function.The unset fields gets default values.
Warning: This function is locked during callbacks.
fixtureDef: (table)
The created fixture instance.
Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts associated with this fixture. This will automatically adjust the mass of the body if the body is dynamic and the fixture has positive density. All fixtures attached to a body are implicitly destroyed when the body is destroyed.
Warning: This function is locked during callbacks.
fixture: (b2.Fixture) the fixture to be removed
Applies a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the angular velocity. This wakes up the body.
forcex: (number) the x coordinate of the world force vector, usually in Newtons (N) forcey: (number) the y coordinate of the world force vector, usually in Newtons (N) pointx: (number) the x coordinate of the world position of the point of application pointy: (number) the y coordinate of the world position of the point of application
Applies a torque. This affects the angular velocity without affecting the linear velocity of the center of mass. This wakes up the body.
torque: (number) about the z-axis (out of the screen), usually in N-m
Applies an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of application is not at the center of mass. This wakes up the body.
impulsex: (number) the x coordinate of the world impulse vector, usually in N-seconds or kg-m/s impulsey: (number) the y coordinate of the world impulse vector, usually in N-seconds or kg-m/s pointx: (number) the x coordinate of the world position of the point of application pointy: (number) the y coordinate of the world position of the point of application
Applies an angular impulse.
impulse: (number) the angular impulse in units of kg*m*m/s
Returns the sleeping state of this body. Returns true
if body is awake (not sleeping), false
otherwise.
The sleeping state of this body.
Set the sleep state of the body. A sleeping body has very low CPU cost.
awake: (boolean) set to true to wake body, false to put it to sleep
Sets the active state of the body. An inactive body is not simulated and cannot be collided with or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive body are implicitly inactive. An inactive body is still owned by a b2.World object and remains in the body list.
flag: (boolean) active flag
Returns the active state of the body.
true
if the body is active, false
otherwise
Returns the linear damping of the body.
The linear damping of the body
Sets the linear damping of the body.
linearDamping: (number) new linear damping of the body
Returns the angular damping of the body.
The angular damping of the body
Sets the angular damping of the body.
angularDamping: (number) new angular damping of the body
Returns the world position of the center of mass.
x and y coordinates of the world position of the center of mass
Returns the local position of the center of mass.
x and y coordinates of the local position of the center of mass
Returns the total mass of the body in kilograms (kg).
The total mass of the body in kilograms (kg)
Returns the rotational inertia of the body about the local origin in kg-m2.
The rotational inertia of the body about the local origin in kg-m2.
Sets the gravity scale of the body.
scale: (number) new gravity scale of the body
Returns the gravity scale of the body.
The gravity scale of the body
Returns the world coordinates of a point given the local coordinates.
x: (number) x coordinate of the local point y: (number) y coordinate of the local point
x and y coordinates of the same point expressed in world coordinates
Returns the world coordinates of a vector given the local coordinates.
x: (number) x coordinate of the local vector y: (number) y coordinate of the local vector
x and y coordinates of the same vector expressed in world coordinates
Returns the local coordinates of a point given the world coordinates.
x: (number) x coordinate of the world point y: (number) y coordinate of the world point
x and y coordinates of the same point expressed in local coordinates
Returns the local coordinates of a vector given the world coordinates.
x: (number) x coordinate of the world vector y: (number) y coordinate of the world vector
x and y coordinates of the same vector expressed in local coordinates
flag: (boolean)
flag: (boolean)
flag: (boolean)
A fixture is used to attach a shape to a body for collision detection. A fixture inherits its transform from its parent. Fixtures hold additional non-geometric data such as friction, collision filters, etc. Fixtures are created via b2.Body:createFixture.
Returns the parent body of this fixture. This is nil
if the fixture is not attached.
The parent body.
Sets if this fixture is a sensor.
sensor: (boolean)
Is this fixture a sensor (non-solid)?
true
if the shape is a sensor, false
otherwise.
Sets the contact filtering data. This will not update contacts until the next time step when either parent body is active and awake. The filter data definition is given as a ordinary table. The fields of the filter data table are:
filterData: (table)
Returns the contact filtering data.
contact filtering data table
A shape is used for collision detection. It is the base class of b2.CircleShape and b2.PolygonShape classes.
You can not create a b2.Shape
instance directly, but instead you create b2.CircleShape and b2.PolygonShape instances.
A convex polygon. It is assumed that the interior of the polygon is to the left of each edge.
Creates a new b2.PolygonShape
instance.
A new b2.PolygonShape
object.
Build vertices to represent an oriented box.
hx: (number) the half-width hy: (number) the half-heigh centerx: (number, default = 0) the x coordinate of the center of the box in local coordinates centery: (number, default = 0) the y coordinate of the center of the box in local coordinates angle: (number, default = 0) the rotation of the box in local coordinates
Copy vertices. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge.
vertices: A list of numbers that contains the x, y coordinates of the vertices sequentially
local polygonShape = b2.PolygonShape.new()
polygonShape:set(1,4, 2,6, 3,7)
A circle shape.
Creates a new b2.CircleShape
instance and optionally set its center point and radius.
If this function is called with more than 3 parameters, b2.CircleShape
instance
is created and its center point and radius are set. If this function is called without any
paramaters, only b2.CircleShape
instance is created and you should set the center
point and radius with b2.CircleShape:set function.
centerx: (number, optional) the x coordinate of the center centery: (number, optional) the y coordinate of the center radius: (number, optional) the radius
A new b2.CircleShape
object.
Sets the center point and radius of this instance.
centerx: (number, optional) the x coordinate of the center centery: (number, optional) the y coordinate of the center radius: (number, optional) the radius
A line segment (edge) shape. These can be connected in chains or loops to other edge shapes.
Creates a new b2.EdgeShape
instance and optionally sets its 2 vertices.
If this function is called with more than 4 parameters, b2.EdgeShape
instance
is created and its 2 vertices are set. If this function is called without any
paramaters, only b2.EdgeShape
instance is created and you should set the 2
vertices with b2.EdgeShape:set function.
v1x: (number, optional) - the x coordinate of 1st point of edge v1y: (number, optional) - the y coordinate of 1st point of edge v2x: (number, optional) - the x coordinate of 2nd point of edge v2y: (number, optional) - the y coordinate of 2nd point of edge
Sets the two vertices of this instance.
v1x: (number) - the x coordinate of 1st point of edge v1y: (number) - the y coordinate of 1st point of edge v2x: (number) - the x coordinate of 2nd point of edge v2y: (number) - the y coordinate of 2nd point of edge
A chain shape is a free form sequence of line segments. The chain has two-sided collision, so you can use inside and outside collision. Therefore, you may use any winding order. Connectivity information is used to create smooth collisions.
Note: The chain will not collide properly if there are self-intersections.
Creates a new b2.ChainShape
object.
Creates a chain with isolated end vertices.
vertices: A list of numbers that contains the x, y coordinates of the vertices sequentially
Creates a loop. This automatically adjusts connectivity.
vertices: A list of numbers that contains the x, y coordinates of the vertices sequentially
The b2.Joint
class is the base joint class. Joints are used to constraint two bodies together in various fashions. Some joints also feature limits and motors.
Returns the type of the concrete joint. The return value can be one of the b2.REVOLUTE_JOINT
, b2.PRISMATIC_JOINT
, b2.DISTANCE_JOINT
, b2.PULLEY_JOINT
,
b2,MOUSE_JOINT
, b2.GEAR_JOINT
, b2.LINE_JOINT
, b2.WELD_JOINT
, b2.FRICTION_JOINT
, b2.ROPE_JOINT
.
The type of the concrete joint
Returns the first body attached to this joint.
The first body attached to this joint
Returns the second body attached to this joint.
The second body attached to this joint
Returns the anchor point on bodyA in world coordinates.
The x and y coordinates of the anchor point
Returns the anchor point on bodyB in world coordinates.
The x and y coordinates of the anchor point
Short-cut function to determine if either body is inactive.
true
if both bodyA and bodyB is active, false
otherwise
Returns the reaction force on bodyB at the joint anchor in Newtons.
inv_dt: (number)
2 values as x and y components of the reaction force on bodyB at the joint anchor in Newtons
Returns the reaction torque on bodyB in N*m.
inv_dt: (number)
The reaction torque on bodyB in N*m
A revolute joint constrains two bodies to share a common point while they are free to rotate about the point. The relative rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is provided so that infinite forces are not generated.
Returns the current joint angle in radians.
The current joint angle in radians
Returns the current joint angle speed in radians per second.
The current joint angle speed in radians per second
Is the joint limit enabled?
true
if joint limit is enabled, false
otherwise
Enables or disables the joint limit.
flag: (boolean) enable flag of joint limit
Returns the lower and upper joint limit in radians.
The lower and upper joint limit in radians
Sets the joint limits in radians.
lower: (number) lower joint limit in radians upper: (number) upper joint limit in radians
Is the joint motor enabled?
true
if joint motor is enabled, false
otherwise
Enables or disables the joint motor.
flag: (boolean) enable flag of joint motor
Sets the motor speed in radians per second.
speed: (number) motor speed in radians per second
Returns the motor speed in radians per second.
The motor speed in radians per second
Sets the maximum motor torque, usually in N-m.
torque: (number) the maximum motor torque, usually in N-m
Returns the current motor torque given the inverse time step. Unit is N*m.
inv_dt: (number)
The current motor torque given the inverse time step. Unit is N*m
A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative rotation is prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction.
Returns the current joint translation, usually in meters.
The current joint translation, usually in meters
Returns the current joint translation speed, usually in meters per second.
The current joint translation speed, usually in meters per second
Is the joint limit enabled?
true
if joint limit is enabled, false
otherwise
Enables or disables the joint limit.
flag: (boolean) enable flag of joint limit
Returns the lower and upper joint limit, usually in meters.
The lower and upper joint limit, usually in meters
Sets the joint limits, usually in meters.
lower: (number) lower joint limit in meters upper: (number) upper joint limit in meters
Is the joint motor enabled?
true
if joint motor is enabled, false
otherwise
Enables or disables the joint motor.
flag: (boolean) enable flag of joint motor
Sets the motor speed in meters per second.
speed: (number) motor speed in meters per second
Returns the motor speed in meters per second.
The motor speed in meters per second
Sets the maximum motor force, usually in N.
force: (number) the maximum motor force, usually in N.
Returns the current motor force given the inverse time step, usually in N.
inv_dt: (number)
The current motor force given the inverse time step, usually in N
A distance joint constrains two points on two bodies to remain at a fixed distance from each other. You can view this as a massless, rigid rod.
Sets the natural length. Manipulating the length can lead to non-physical behavior when the frequency is zero.
length: (number) the length of this distance joint, usually in meters.
Returns the length of this distance joint, usually in meters.
The length of this distance joint, usually in meters
Sets the mass-spring-damper frequency in Hertz.
frequency: (number) the mass-spring-damper frequency in Hertz
Returns the mass-spring-damper frequency of this distance joint in Hertz.
The mass-spring-damper frequency in Hertz.
Sets the damping ratio of this distance joint. 0 = no damping, 1 = critical damping.
ratio: (number) the damping ratio
Returns the damping ratio of this distance joint.
The damping ratio of this distance joint
The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio * length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top.
Returns the x and y coordinates of the first ground anchor.
The x and y coordinates of the first ground anchor
Returns the x and y coordinates of the second ground anchor.
The x and y coordinates of the second ground anchor
Returns the current length of the segment attached to bodyA.
The current length of the segment attached to bodyA
Returns the current length of the segment attached to bodyB.
The current length of the segment attached to bodyB
Returns the pulley ratio.
The pulley ratio
A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces.
Updates the target point.
x: (number) x coordinate of the target point y: (number) y coordinate of the target point
Returns the x and y coordinates of the target point.
The x and y coordinates of the target point
Sets the maximum force in Newtons.
force: (number) the maximum force in Newtons
Returns the maximum force in Newtons.
The maximum force in Newtons.
Sets the response speed in Hertz.
frequency: (number) the response speed in Hertz
Returns the response speed in Hertz.
The response speed in Hertz
Sets the damping ratio. 0 = no damping, 1 = critical damping.
ratio: (number) the damping ratio
Returns the damping ratio. 0 = no damping, 1 = critical damping.
The damping ratio
A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify a gear ratio to bind the motions together: coordinate1 + ratio * coordinate2 = constant The ratio can be negative or positive. If one joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of 1/length.
Sets the gear ratio.
ratio: (number) the gear ratio
Returns the gear ratio.
The gear ratio
A wheel joint provides two degrees of freedom: translation along an axis fixed in bodyA and rotation in the plane. You can use a joint limit to restrict the range of motion and a joint motor to drive the rotation or to model rotational friction. This joint is designed for vehicle suspensions.
Returns the current joint translation in meters.
The current joint translation in meters
Returns the current joint translation speed in meters per second.
The current joint translation speed in meters per second
Is the joint motor enabled?
true
if joint motor is enabled, false
otherwise
Enables or disables the joint motor.
flag: (boolean) enable flag of joint motor
Sets the motor speed in radians per second.
speed: (number) motor speed in radians per second
Returns the motor speed in radians per second.
The motor speed in radians per second
Sets the maximum motor torque in N-m.
torque: (number) the maximum motor torque in N-m
Returns the maximum motor torque in N-m.
The maximum motor torque in N-m
Sets the spring frequency in hertz. Setting the frequency to zero disables the spring.
frequency: (number) spring frequency in hertz
Returns the spring frequency in hertz.
The spring frequency in hertz.
Sets the spring damping ratio.
damping: (number) damping ratio
Returns the spring damping ratio.
The spring damping ratio
A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island constraint solver is approximate.
Sets frequency in Hz.
frequency: (number) frequency in Hz
Returns frequency in Hz.
Frequency in Hz
Sets damping ratio.
damping: (number) damping ratio
Returns damping ratio.
Damping ratio
Friction joint. This is used for top-down friction. It provides 2D translational friction and angular friction.
Sets the maximum friction force in N.
force: (number) the maximum friction force in N
Returns the maximum friction force in N.
The maximum friction force in N
Sets the maximum friction torque in N*m.
torque: (number)the maximum friction torque in N*m
Returns the maximum friction torque in N*m.
The maximum friction torque in N*m
A rope joint enforces a maximum distance between two points on two bodies. It has no other effect. Warning: if you attempt to change the maximum length during the simulation you will get some non-physical behavior. A model that would allow you to dynamically modify the length would have some sponginess, so I chose not to implement it that way. See b2.DistanceJoint if you want to dynamically control length.
Sets the maximum length of the rope.
maxLength: (number)
Returns the maximum length of the rope.
The maximum length of the rope.
The b2.DebugDraw
class is used to provide debug drawing of physical entities in your application.
local debugDraw = b2.DebugDraw.new()
world:setDebugDraw(debugDraw)
stage:addChild(debugDraw)
Creates a new b2.DebugDraw
instance.
Sets the debug drawing flags. These flags are available:
b2.DebugDraw.SHAPE_BIT
b2.DebugDraw.JOINT_BIT
b2.DebugDraw.AABB_BIT
b2.DebugDraw.PAIR_BIT
b2.DebugDraw.CENTER_OF_MASS_BIT
b2.DebugDraw.SHAPE_BIT
is set by default.
Because Lua doesn’t support bitwise operations by default, you can use +
operator to combine flags.
flags: (number) debug draw flags
local debugDraw = b2.DebugDraw.new()
debugDraw:setFlags(b2.DebugDraw.SHAPE_BIT + b2.DebugDraw.JOINT_BIT)
Returns the debug drawing flags.
The debug drawing flags
Append flags to the current flags.
flags: (number) debug draw flags
Clear flags from the current flags.
flags: (number) debug draw flags
The class manages contact between two shapes. A contact exists for each overlapping AABB in the broad-phase (except if filtered). Therefore a contact object may exist that has no contact points.
Returns the contact manifold as a table. This table contains points
, localNormal
, localPoint
and type
fields.
Returns the world manifold as a table. This table contains normal
and points
fields.
Returns whether the contact is touching or not.
Whether the contact is touching or not.
Enables/disables the contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the current time step (or sub-step in continuous collisions).
flag: (boolean)
Returns fixture A in this contact.
Fixture A in this contact.
Returns the child primitive index for fixture A.
The child primitive index for fixture A.
Returns fixture B in this contact.
Fixture B in this contact.
Returns the child primitive index for fixture B.
The child primitive index for fixture B.
Overrides the default friction mixture. You can call this in pre-solve event. This value persists until set or reset.
friction: (number)
Returns the friction.
The friction.
Resets the friction mixture to the default value.
Overrides the default restitution mixture. You can call this in pre-solve event. This value persists until set or reset.
restitution: (number)
Returns the restitution.
The restitution.
Resets the restitution mixture to the default value.
The Geolocation
class is used to configure the parameters and dispatching of location and heading related events.
Event.LOCATION_UPDATE = "locationUpdate"
Event.HEADING_UPDATE = "headingUpdate"
Event.ERROR = "error"
LOCATION_UPDATE
event contains the fields latitude
, longitude
and altitude
.
HEADING_UPDATE
event contains the fields magneticHeading
and trueHeading
.
geolocation = Geolocation.new()
local function onLocationUpdate(event)
print("location: ", event.latitude, event.longitude, event.altitude)
end
local function onHeadingUpdate(event)
print("heading: ", event.magneticHeading, event.trueHeading)
end
geolocation:addEventListener(Event.LOCATION_UPDATE, onLocationUpdate)
geolocation:addEventListener(Event.HEADING_UPDATE, onHeadingUpdate)
geolocation:start()
Returns true
if the device has the capability to determine current location and this capability is enabled, false
otherwise.
true
if geolocation is available, false
otherwise
Returns true
if the device has the capability to determine heading, false
otherwise.
true
if heading is available, false
otherwise
Sets the desired accuracy (in meters) of the location data. The receiver does its best to achieve the requested accuracy. However the actual accuracy is not guaranteed. The default value is 0 (best accuracy).
accuracy: (number) the desired accuracy
Returns the previously set desired accuracy.
The previously set desired accuracy
Sets the minimum distance (in meters) threshold. If threshold distance is greater than 0, a location event will only be dispatched if the device moves by threshold. The default value is 0 (as frequently as possible).
threshold: (number) the minimum distance threshold
Returns the previously set minimum distance threshold.
The previously set minimum distance threshold
Starts the generation of updates that report the current location and heading.
Stops the generation of updates that report the current location and heading.
Starts the generation of updates that report the current location.
Stops the generation of updates that report the current location.
Starts the generation of updates that report the heading.
Stops the generation of updates that report the heading.
The Gyroscope
class is used to access gyroscope data.
local gyroscope = Gyroscope.new()
gyroscope:start()
local angx = 0
local angy = 0
local angz = 0
local function onEnterFrame(event)
local x, y, z = gyroscope:getRotationRate()
angx = angx + x * event.deltaTime
angy = angy + y * event.deltaTime
angz = angz + z * event.deltaTime
print(angx * 180 / math.pi, angy * 180 / math.pi, angz * 180 / math.pi)
end
stage:addEventListener("enterFrame", onEnterFrame)
Returns true
if gyroscope is available for this platform, false
otherwise.
true
if gyroscope is available for this platform, false
otherwise.
Starts the generation of gyroscope samples.
Stops the generation of gyroscope samples.
Returns the device’s rate of rotation around three axes in radians per second.
3 values as rate of rotation around x, y and z axes
The Accelerometer
class is used to access accelerometer data.
local accelerometer = Accelerometer.new()
accelerometer:start()
---
local x, y, z = accelerometer:getAcceleration()
print(x, y, z)
Returns true
if accelerometer is available for this platform, false
otherwise.
true
if accelerometer is available for this platform, false
otherwise.
Starts the generation of accelerometer samples.
Stops the generation of accelerometer samples.
Returns the 3-axis acceleration measured by the accelerometer.
3 values as x-axis, y-axis and z-axis acceleration in G’s
KeyCode table holds the key code constants. These map directly to a physical key on the keyboard.
KeyCode.BACK
Back key on AndroidKeyCode.SEARCH
Search key on AndroidKeyCode.MENU
Menu key on AndroidKeyCode.CENTER
Center key on AndroidKeyCode.SELECT
Select key on AndroidKeyCode.START
Start key on AndroidKeyCode.L1
L1 key on AndroidKeyCode.R1
R1 key on AndroidKeyCode.LEFT
Left arrow keyKeyCode.UP
Up arrow keyKeyCode.RIGHT
Right arrow keyKeyCode.DOWN
Down arrow keyKeyCode.X
X keyKeyCode.Y
Y keyThe AlertDialog
class is used to display native alert dialogs with one, two or three buttons. Cancel button
is mandatory but other two buttons are optional. When the user presses any button in the alert dialog,
it’s dismissed and ‘Event.COMPLETE’ event is dispatched:
event.buttonIndex
: the index of the button pressed. It is nil
when cancel button is pressed, 1 when 1st button is pressed and 2 when 2nd button is pressed.event.buttonText
: the text of the button pressedIf alert dialog is dismissed by any other means (by pressing back button on Android or by pressing close button on desktop), it behaves as cancel button is pressed.
local alertDialog = AlertDialog.new("This is my title", "And my message", "Cancel", "Yes", "No")
local function onComplete(event)
print(event.buttonIndex, event.buttonText)
end
alertDialog:addEventListener(Event.COMPLETE, onComplete)
alertDialog:show()
Creates a new AlertDialog
object.
title: (string) The string that appears in the receiver's title bar. Can be empty string. message: (string) Descriptive text that provides more details than the title. Can be empty string. cancelButton: (string) The text of the cancel button. button1: (string, optional) The text of the 1st optional button. button2: (string, optional) The text of the 2st optional button.
Shows the alert dialog.
Hides the alert dialog.
The TextInputDialog
class is used to display native text input dialogs with one text edit field, one button (as cancel button)
and two optional buttons. When the user presses any buttons in the alert dialog, it’s dismissed and ‘Event.COMPLETE’ event is dispatched:
event.text
: the text entered into text input fieldevent.buttonIndex
: the index of the button pressed. It is nil
when cancel button is pressed, 1 when 1st button is pressed and 2 when 2nd button is pressed.event.buttonText
: the text of the button pressedIf text input dialog is dismissed by any other means (by pressing back button on Android or by pressing close button on desktop), it behaves as cancel button is pressed.
local textInputDialog = TextInputDialog.new("my title", "my message", "some text", "Cancel", "OK")
local function onComplete(event)
print(event.text, event.buttonIndex, event.buttonText)
end
textInputDialog:addEventListener(Event.COMPLETE, onComplete)
textInputDialog:show()
Creates a new TextInputDialog
object.
title: (string) The string that appears in the receiver’s title bar. message: (string) Descriptive text that provides more details than the title. text: (string) The text on the text field. cancelButton: (string) The text of the cancel button. button1: (string, optional) The text of the 1st optional button. button2: (string, optional) The text of the 2st optional button.
Sets the text on the text field.
text: (string) The text on the text field.
Returns the text on the text field.
The text on the text field.
Sets the input (keyboard) type associated with the text field. The options are:
TextInputDialog.TEXT
: Default keyboard typeTextInputDialog.NUMBER
: Numeric keypadTextInputDialog.PHONE
: Keypad designed for entering telephone numbersTextInputDialog.EMAIL
: Keyboard optimized for specifying email addressesTextInputDialog.URL
: Keyboard optimized for URL entrytype: (string) Tnput type associated with the text field.
Returns the keyboard type associated with the text field.
The keyboard type associated with the text field.
Sets whether the text object should hide the text being entered.
secureInput: (boolean) If 'true', the text object hides the text being entered.
Returns whether the text object hides the text being entered.
Whether the text object hides the text being entered.
This table stores all the functions related to Flurry analytics library.
Flurry is available only for iOS as an external plugin. To use flurry:
To load the Flurry library, call require "flurry"
.
Returns true
if Flurry is available for this platform. Currently, Flurry is available only for iOS.
true
if Flurry is available for this platform, false
otherwise.
Starts the Flurry session with your API key. To create an account on Flurry and to obtain the API key specific to your application, please visit http://www.flurry.com and follow the instructions there.
You need to call this function once after your application starts. For example, init.lua
is suitable to call this function.
apiKey: (string) The Flurry API key.
Use this function to count the number of times certain events happen during a session of your application and to pass dynamic parameters to be recorded with that event. Event parameters is optional and can be passed in as a table value. Your application is currently limited to counting occurrences for 100 different event ids (maximum length 255 characters). Maximum of 10 event parameters per event is supported.
To start a timed event, pass timed
parameter as true
.
eventName: (string) The event name to be logged at Flurry service. parameters: (table, optional) Optional paramaters to be recorted with this event. timed: (boolean, optional) Specifies this is a timed event.
require "flurry"
flurry.logEvent("myEvent1")
flurry.logEvent("myEvent2", {key="value"})
flurry.logEvent("myEvent3", {key="value"}, true)
Use this function to end timed event before app exists, otherwise timed events automatically end when app exists. When ending the timed event, a new event parameters table can be used to update event parameters. If you don’t specify a new event parameters table, event parameters are kept the same.
eventName: (string) The event name of end timed event. parameters: (table, optional) If specified, event paramaters updated for this event.
Gideros runtime supports public domain SQLite3 database engine for iOS, Android and Desktop platforms. For more information and detailed documentation, please visit http://lua.sqlite.org.
Currently, LuaSQLite3 plugin cannot open databases stored in APK files. Therefore, database file should be copied from resource directory to documents directory.
To copy a file, this function can be used:
local function copy(src, dst)
local srcf = io.open(src, "rb")
local dstf = io.open(dst, "wb")
local size = 2^13 -- good buffer size (8K)
while true do
local block = srcf:read(size)
if not block then break end
dstf:write(block)
end
srcf:close()
dstf:close()
end
Also it’s better to check if the database file is previously copied or not. To check if a file can be found on the underlying file system, this function can be used:
local function exists(file)
local f = io.open(file, "rb")
if f == nil then
return false
end
f:close()
return true
end
By using these two function, you can copy the database file from resource to documents directory before using it:
if not exists("|D|database.db") then
copy("database.db", "|D|database.db")
end
The StoreKit
class provides the functionality that allow an application to request payment from a user.
This class is only available to iOS platforms.
The StoreKit
class is defined in module “storekit”. Therefore, you need to call
require("storekit")
before using it. Loading the “storekit” module
also creates a global variable storekit
of type StoreKit
for direct use.
The state of a transaction is defined by 3 string constants:
event.errorCode
and event.errorDescription
fields to determine what happened.event.originalTransaction
field to obtain information about the original purchase.The StoreKit
class dispatches the events Event.REQUEST_PRODUCTS_COMPLETE
, Event.TRANSACTION
and Event.RESTORE_TRANSACTIONS_COMPLETE
.
The function StoreKit:requestProducts is used to retrieve localized information about a list of products from the Apple App Store.
When the request completes, Event.REQUEST_PRODUCTS_COMPLETE
event is dispatched. The resulting event table contains
these additional fields about the products:
Each table in event.products
array contains these fields:
For example, this code can be used to print the retrieved product information:
local function onRequestProductsComplete(event)
if event.errorCode ~= nil then
print("error", event.errorCode, event.errorDescription)
return
end
print("products:")
for i=1,#event.products do
print("title", event.products[i].title)
print("description", event.products[i].description)
print("price", event.products[i].price)
print("productIdentifier", event.products[i].productIdentifier)
end
print("invalidProductIdentifiers:")
for i=1,#event.invalidProductIdentifiers do
print(event.invalidProductIdentifiers[i])
end
end
This event is dispatched when a transaction is updated. The event listener should process all successful transactions, unlock the functionality purchased by the user, and then finish the transaction by calling StoreKit:finishTransaction method. The resulting event table can contain these additional fields about the products:
event.transaction.state
is set to StoreKit.FAILED
event.transaction.state
is set to StoreKit.FAILED
This code can be used to print the transaction information and unlock the functionality purchased by the user:
local function onTransaction(event)
print("payment.productIdentifier", event.payment.productIdentifier)
print("payment.quantity", event.payment.quantity)
print("transaction.state", event.transaction.state)
if event.transaction.state == StoreKit.FAILED then
print("error", event.errorCode, event.errorDescription)
else
print("transaction.identifier", event.transaction.identifier)
print("transaction.date", event.transaction.date)
if event.transaction.state == StoreKit.PURCHASED then
print("transaction.receipt", event.transaction.receipt)
end
if event.transaction.state == StoreKit.RESTORED then
print("originalTransaction.identifier", event.originalTransaction.identifier)
print("originalTransaction.date", event.originalTransaction.date)
end
-- unlock the functionality purchased by the user
end
storekit:finishTransaction(event.transaction)
end
This event is dispatched after the transactions are delivered. The resulting event table can contain these additional fields:
If all transactions are delivered successfully, event.errorCode
and event.errorDescription
will be nil
.
Returns whether the user is allowed to make payments.
true
if the user is allowed to authorize payment. false
if they do not have permission.
Retrieve localized information about a list of products from the Apple App Store. When the request completes, Event.REQUEST_PRODUCTS_COMPLETE
event is dispatched.
productIdentifiers: (table) An array of product identifiers for the products you wish to retrieve descriptions of.
Process a payment request. When that transaction is complete or if a failure occurs, Event.TRANSACTION
event is dispatched.
productIdentifier: (string) A string used to identify a product that can be purchased from within your application. quantity: (number, default = 1) The number of items the user wants to purchase. This value should be greater than or equal to 1.
Restore previously completed purchases. Event.TRANSACTION
event is dispatched for each previously completed transaction that can be restored.
Each transaction includes a copy of the original transaction.
After the transactions are delivered, Event.RESTORE_TRANSACTIONS_COMPLETE
event is dispatched. If an error occurred while restoring transactions, event.errorCode
and
event.errorDescription
fields contain the details of the error.
Completes a pending transaction. Your application should call this function only after it has successfully processed the transaction and unlocked the functionality purchased by the user.
transaction: (table) transaction information recevied with the event Event.TRANSACTION.
iAd module for iOS allows you to use iAd framework that was introduced in iOS 4.0. To load the iAd module, call require "iad"
. After loading iAd module, iad
table stores all
classes and functions related to iAd framework.
Returns true
if iAd framework is available for this platform, false
otherwise. For iOS 4.0+, this function returns true
.
true
if iAd framework is available for this platform, false
otherwise
The iad.Banner
class provides a view that displays banner advertisements to the user. When the user taps a banner view, the view triggers an action
programmed into the advertisement. For example, an advertisement might show a movie, present a modal advertisement, or launch Safari to show a webpage.
Your application is notified when an action starts and stops, but does not otherwise interact with the advertisement.
Creates an iad.Banner
instance. If iAd framework is not available, this function gives an error.
The alignment and the orientation of the ad banner are defined by these 4 string constants:
iad.Banner.TOP = "top"
iad.Banner.BOTTOM = "bottom"
iad.Banner.PORTRAIT = "portrait"
iad.Banner.LANDSCAPE = "landscape"
And iad.Banner
class dispatches these 4 events:
Event.BANNER_AD_LOADED = "bannerAdLoaded"
Event.BANNER_AD_FAILED = "bannerAdFailed"
Event.BANNER_ACTION_BEGIN = "bannerActionBegin"
Event.BANNER_ACTION_FINISHED = "bannerActionFinished"
When an ad banner is created, iAd will start requesting ads. Apple serves ads, and refreshes with new ads, on an automatic timer. Apple also requires that the ad area be hidden when no ad is available to display. iAd module manages all this behavior for you automatically.
When an ad becomes available, it will be displayed on the screen, the event Event.BANNER_AD_LOADED
is dispatched when one is about to be displayed,
or the event Event.BANNER_AD_FAILED
is dispatched when the loading has failed. If the loading has failed, the fields event.errorCode
and event.errorDescription
contains information about the failure reason.
When the user clicks on an ad, the event Event.BANNER_ACTION_BEGIN
is dispatched. At this time, the user will either be taken out of your application
to view the app store (in this case event.willLeaveApplication
field will be true), or they will be presented with a fullscreen advertisement to interact with,
and event.willLeaveApplication
will be false. In the latter case, you may decide to pause the application until the event Event.BANNER_ACTION_FINISHED
is dispatched.
alignment: (string) whether you want ads to show top or bottom of the screen. It can be either iad.Banner.TOP or iad.Banner.BOTTOM. orientation: (string) orientation of the banner. It can be either iad.Banner.PORTRAIT or iad.Banner.LANDSCAPE.
-- if the platform is iOS, load the iAd module
if application:getDeviceInfo() == "iOS" then
require "iad"
end
-- 4 event listeners for debug print
local function onBannerAdLoaded()
print("banner ad loaded")
end
local function onBannerAdFailed(event)
print("banner ad failed", event.errorCode, event.errorDescription)
end
local function onBannerActionBegin(event)
print("banner action begin", event.willLeaveApplication)
end
local function onBannerActionFinished()
print("banner action finished")
end
-- if iAd module is loaded and iAd framework is available, create an ad banner and then show it
local banner = nil
if iad and iad.isAvailable() then
banner = iad.Banner.new(iad.Banner.TOP, iad.Banner.PORTRAIT)
banner:addEventListener(Event.BANNER_AD_LOADED, onBannerAdLoaded)
banner:addEventListener(Event.BANNER_AD_FAILED, onBannerAdFailed)
banner:addEventListener(Event.BANNER_ACTION_BEGIN, onBannerActionBegin)
banner:addEventListener(Event.BANNER_ACTION_FINISHED, onBannerActionFinished)
banner:show() -- show it because newly created banners are not visible by default
end
-- show the banner (if it exists)
function showBanner()
if banner ~= nil then
banner:show()
end
end
-- hide the banner (if it exists)
function hideBanner()
if banner ~= nil then
banner:hide()
end
end
Shows the ad banner if an ad is currently available or when an ad becomes available.
Hides the ad banner.
Sets the alignment of the banner as the top or bottom.
alignment: (string) whether you want ads to show top or bottom of the screen. It can be either iad.Banner.TOP or iad.Banner.BOTTOM.
Returns true
if the ad banner has downloaded an advertisement, false
otherwise.
true
if the ad banner has downloaded an advertisement, false
otherwise
Facebook SDK plugin is available for only iOS as an external plugin. To use facebook module:
The Facebook
class is defined in module “facebook”. Therefore, you need to call
require("facebook")
before using it. Loading the Facebook module
also creates a global variable facebook
of type Facebook
for direct use.
The Facebook
class dispatches the following events:
Dispatched when the user has logged in with Facebook.
Dispatched when Facebook login fails.
Dispatched when the user cancelled Facebook login.
Dispatched when the user has logged out with Facebook.
Dispatched when a Facebook dialog has finished.
Dispatched when a Facebook dialog has failed. event.errorCode
and event.errorDescription
fields give detailed information about the fail reason.
Dispatched when a Facebook dialog is cancelled.
Dispatched when a Facebook graph request returns a response. event.response
field contains the raw response of the completed Facebook graph request.
Dispatched when a Facebook graph request has failed. event.errorCode
and event.errorDescription
fields give detailed information about the fail reason.
Initializes the Facebook library and sets App ID. This function should be called first before other functions.
appId: (string) The Facebook application id.
Starts the authorization flow for the user with the requested permissions.
permissions: (table, optional) An array of the requested permissions.
Invalidates the current user session. This method does not unauthorized the application, it simply invalidates the access token. The user can unauthorized the application through the app settings page on the Facebook website.
Checks if the access token is available and has not expired.
true
if the access token is valid, false
otherwise.
Generate a UI dialog for the desired action.
action: (string) The type of dialog to call. Currently supported methods are oauth, feed, and apprequests. paramaters: (table, optional) Table representing parameters specific to a particular dialog.
Makes a request to the Graph API.
graphPath: (string) The path to the Graph API endpoint. For example, to fetch data about the currently logged in user this parameter should be ''me'', representing a call to the https://graph.facebook.com/me endpoint. paramaters: (table, optional) Table representing the API call parameters. method: (string, optional) HTTP method.
Sets the access token.
accessToken: (string)
Returns the access token.
The access token.
Sets the expiration date.
expirationDate: (string)
Returns the expiration date;
The expiration date if it’s set, nil
otherwise.
Extends the access token.
Attempts to extend the access token. The access token expires after a certain amount of time and when you call this method it will be refreshed if it is still active and only after some time has passed since the last refresh. To ensure that you keep the access token fresh for active users, call this method in your Application.RESUME
event.
Returns if the access token should be extended.
true
if the access token should be extended, false
otherwise.
The GoogleBilling
class is defined in the module “googlebilling”. Therefore, you need to call
require("googlebilling")
before using it. Loading the Google Billing module
also creates a global variable googlebilling
of type GoogleBilling
for direct use.
GoogleBilling
class dispatches 5 events: Event.CHECK_BILLING_SUPPORTED_COMPLETE
,
Event.REQUEST_PURCHASE_COMPLETE
,Event.RESTORE_TRANSACTIONS_COMPLETE
,
Event.CONFIRM_NOTIFICATION_COMPLETE
and Event.PURCHASE_STATE_CHANGE
.
Event.*_COMPLETE
events contains a field event.responseCode
which provides status information
and error information about a request. Response code can be one of these values:
GoogleBilling.OK
: Indicates that the request was sent to the server successfully. When this code is returned
in response to a checkBillingSupported
function, indicates that billing is supported.GoogleBilling.USER_CANCELED
: Indicates that the user pressed the back button on the checkout page instead of buying the item.GoogleBilling.SERVICE_UNAVAILABLE
: Indicates that the network connection is down.GoogleBilling.BILLING_UNAVAILABLE
: Indicates that in-app billing is not available because the API version that
you specified is not recognized by the Google Play application or the user is ineligible for in-app billing
(for example, the user resides in a country that prohibits in-app purchases).GoogleBilling.ITEM_UNAVAILABLE
: Indicates that Google Play cannot find the requested item in the application’s product list.
This can happen if the product ID is misspelled in your requestPurchase
function or if an item is unpublished in the application’s product list.GoogleBilling.DEVELOPER_ERROR
: Indicates that an application is trying to make an in-app billing request but the application has not declared the
com.android.vending.BILLING permission in its manifest. Can also indicate that an application is not properly signed,
or that you sent a malformed request, such as a request with missing Bundle keys or a request that uses an unrecognized request type.GoogleBilling.ERROR
: Indicates an unexpected server error. For example, this error is triggered if you try to purchase an item from yourself, which is not allowed by Google Wallet.Dispatched when checkBillingSuported
function completes. It contains event.responseCode
and event.productType
fields.
Dispatched when requestPurchase
function completes. It contains event.responseCode
, event.productId
, event.productType
and event.developerPayload
fields.
Dispatched when restoreTransactions
function completes. It contains event.responseCode
fields.
Dispatched when confirmNotification
function completes. It contains event.responseCode
and event.notificationId
fields.
Dispatched when information about a transaction is received. It contains event.purchaseState
, event.productId
, event.notificationId
, event.purchaseTime
and event.developerPayload
fields.
Sets the public key. You can find the public key portion of this key pair on your Google Play account’s profile page.
publicKey: (string) Your Google Play public key
Sets the API version. You can find more information http://developer.android.com/guide/google/play/billing/billing_reference.html#billing-versions
apiVersion: (number)
This request verifies that the Google Play application supports in-app billing. You usually send this request when your application first starts up. This request is useful if you want to enable or disable certain UI features that are relevant only to in-app billing.
productType: (string, optional) The item type. It can be GoogleBilling.INAPP or GoogleBilling.SUBS.
true
if in-app billing service is available, false
otherwise.
This request sends a purchase message to the Google Play application and is the foundation of in-app billing. You send this request when a user indicates that he or she wants to purchase an item in your application. Google Play then handles the financial transaction by displaying the checkout user interface.
productId: (string) productType: (string, optional) developerPayload: (string, optional)
true
if in-app billing service is available, false
otherwise.
This request acknowledges that your application received the details of a purchase state change.
notificationId: (string)
true
if in-app billing service is available, false
otherwise.
This request retrieves a user’s transaction status for managed purchases. You should send this message only when you need to retrieve a user’s transaction status, which is usually only when your application is reinstalled or installed for the first time on a device.
true
if in-app billing service is available, false
otherwise.