Wiki
Clone wikiCore / Documentation
Graphics
Drawing Shapes, Styles and Positioning
How Codea Draws
Description
When you begin a new project in Codea you'll notice that it consists of a tab called Main and some template code. Your project can consist of several tabs, the initial one is always called Main. If you add more files they will be listed across the top.
function setup()
print("Hello World!")
end
function draw()
background(0,0,0)
-- Do your drawing here
end
This is the framework that your project will use to run. There are two functions defined for you initially: setup() and draw().
setup() and draw() are executed by Codea when you press the play button to run your project. The setup() function is called once, at the start, and then the draw() function is called repeatedly (60 times per second, to be exact). In setup() Codea expects you to set up your initial program state, and in draw() you can tell Codea to render graphics onto the screen, update your program state over time, and so on.
In the next two sections we will cover these functions in detail.
Related
The draw() function
Description
When you press the play button, the draw() function is repeatedly executed by Codea. Codea tries to execute the draw() function 60 times per second - if it can. Codea can't guarantee that your draw() function will be called 60 times per second (it may slow down if your project performs a lot of computation, or creates highly complex drawing).
function draw()
-- Set the background color to blue-ish
background(100,120,180)
-- Set the fill color to red
fill(255,0,0)
-- Set a wide outline
strokeWidth(5)
-- Set the outline color to white
stroke(255)
-- Draw a red circle with a white outline
-- In the center of the screen
ellipse( WIDTH/2, HEIGHT/2, 200 )
end
Note that the above code will run 60 times every second. That is, you are telling Codea to paint the background blue and draw a red circle with a white outline 60 times per second, from scratch. It does this so that you can create smooth motion by changing your program state over time, and updating your drawing code to reflect the new state. For example, you might make the circle bounce on the ground by changing its Y-position (the second parameter to ellipse()) every frame.
Related
The setup() function
Description
When you press the play button Codea will call the setup() function once, before it begins calling the draw() function. In here you can perform any once-off computations, set up program state, set the display mode, and do things that you don't need to do every frame. For example, the setup() function below creates a global variable controlled by a slider. This variable is then used in the draw() function to control the Y-position of a circle.
function setup()
displayMode(STANDARD)
parameter("YPosition", 0, HEIGHT, HEIGHT/2)
end
function draw()
background(0)
fill(255,0,0)
ellipse( WIDTH/2, YPosition, 200 )
end
Related
clip( x, y, width, height )
Description
Constrains all drawing performed after this function call to the rectangle specified by x, y, width, height. Any drawing that occurs outside the bounds will not be visible.
This can be used to make split-screen multiplayer games, for example. When called with zero arguments clip() disables the clipping rectangle, allowing drawing to occur anywhere on the screen.
Syntax
clip( x, y, width, height )
clip() --Disables clipping
Parameters
Name | Description |
---|---|
x | integer, x coordinate of the lower-left corner of the clipping rectangle |
y | integer, y coordinate of the lower-left corner of the clipping rectangle |
width | integer, width of the clipping rectangle |
height | integer, height of the clipping rectangle |
setContext( image )
Examples
-- Creates an image of an ellipse and rect
function createImage()
myImage = image(400,400)
setContext( myImage )
ellipse(200, 200, 200)
rect(0, 0, 100, 100)
setContext()
return myImage
end
Description
This call causes all drawing operations to take place on the specified image instead of on-screen. Drawing commands such as ellipse, sprite and rect will render into the image given as an argument to setContext().
Calling setContext() with no arguments causes all drawing operations to return to their regular on-screen drawing functionality. Because Codea uses pre-multiplied drawing, any image passed to setContext() will have its premultiplied flag set to true.
Syntax
setContext()
setContext( image )
Parameters
Name | Description |
---|---|
image | image, all drawing operations will occur on this image instead of on screen |
Related
noise( x, y, z )
Description
Returns a Perlin noise value in the range -1.0 to 1.0 sampled at location x, y, z. Any parameters not provided to this function are treated as zero.
Syntax
noise( x )
noise( x, y )
noise( x, y, z )
Parameters
Name | Description |
---|---|
x | float, x location of the sample |
y | float, y location of the sample |
z | float, z location of the sample |
Returns
Perlin noise value from -1.0 to 1.0 at the given location.
backingMode( mode )
Description
Sets the backing mode to retained or standard. Retained backing will keep the results of the previous frame and is useful if no background function is called in draw. Using retained backing will impact your framerate.
Syntax
backingMode( STANDARD | RETAINED )
Parameters
Name | Description |
---|---|
mode | Optional: either STANDARD or RETAINED |
Returns
The current backing mode if no mode parameter given, otherwise nothing
Related
background( red, green, blue )
Examples
function draw()
-- Dark blueish background
background(0, 50, 70)
-- Do some drawing
end
Description
Clears the background to the specified color. You should generally call this at the start of your draw() function in order to clear the contents of the previous frame.
Syntax
background( gray )
background( gray, alpha )
background( red, green, blue )
background( red, green, blue, alpha )
background( color )
Parameters
Name | Description |
---|---|
gray | int from 0 to 255, specifies value between white and black |
alpha | int from 0 to 255, specifies opacity of the background |
red | int from 0 to 255, specifies red amount of the background |
green | int from 0 to 255, specifies green amount of the background |
blue | int from 0 to 255, specifies blue amount of the background |
color | a value of the color datatype |
Related
ellipse( x, y, width, height )
Description
Draws an ellipse centered at x, y with horizontal and vertical dimensions specified by width and height. The ellipseMode() function sets how these parameters are interpreted. Use fill() to set the color of an ellipse and stroke() to set its outline color.
Syntax
ellipse( x, y, diameter )
ellipse( x, y, width, height )
Parameters
Name | Description |
---|---|
x | x-coordinate of the ellipse |
y | y-coordinate of the ellipse |
width | width of the ellipse |
height | height of the ellipse |
Related
rect( x, y, width, height )
Description
Draws a rectangle with its lower-left corner positioned at x, y and sized at width, height. Use fill() to set the color of a rectangle and stroke() to set the outline color. The interpretation of a rectangle's x, y, width and height parameters can be specified using the rectMode() function. rectMode() is set to CORNER by default.
Syntax
rect( x, y, width, height )
Parameters
Name | Description |
---|---|
x | x-coordinate of the lower-left corner |
y | y-coordinate of the lower-left corner |
width | width of the rectangle |
height | height of the rectangle |
Related
sprite( name, x, y )
Examples
background(127, 127, 127, 255)
sprite("Planet Cute:Character Boy",
WIDTH / 2, HEIGHT / 2)
background(127, 127, 127, 255)
tint(255, 0, 0)
sprite("Planet Cute:Character Boy",
WIDTH / 2, HEIGHT / 2)
Description
Draws a sprite. A sprite is a a bitmap graphic such as a character or space ship. The name of the sprite specifies the sprite pack and sprite to use. Alternatively, an image can be passed in instead of a name to draw that image instead.
By default the x and y parameters set the location of the center of the sprite, the origin mode can be set using the spriteMode() function. The last two parameters are optional and set the width and height in pixels, if these are not specified the sprite will be rendered at the pixel dimensions of its graphic. Sprites can be tinted with the tint() function.
Syntax
sprite( name, x, y )
sprite( name, x, y, width )
sprite( name, x, y, width, height )
sprite( image, x, y )
sprite( image, x, y, width )
sprite( image, x, y, width, height )
Parameters
Name | Description |
---|---|
name | name of the sprite to use, in the following format: |
"SpritePack:SpriteName"
image | image to draw onto the screen |
x | x-coordinate of the center of the sprite (this can be changed with spriteMode) |
y | y-coordinate of the center of the sprite (this can be changed with spriteMode) |
width | optional width of the sprite in pixels |
height | optional width of the sprite in pixels. If width is specified and height is not, then height is automatically computed to preserve the aspect ratio of the image. |
Related
text( string, x, y )
Examples
background(100, 120, 160)
font("Georgia")
fill(255)
fontSize(20)
textWrapWidth(70)
text("Hello World!", WIDTH/2, HEIGHT/2)
Description
Draws text at the given x, y location. You can set the font used by text() with the font() function. Text appearance can be further configured by using the fontSize() and fill() functions.
You can change the alignment and wrapping of text by using textAlign() and textWrapWidth(). If textWrapWidth() is set to 0 (the default) text will be drawn on one line. If textWrapWidth() is set to a value greater than 0 the text will word-wrap if it exceeds the width specified by textWrapWidth()
By default the x and y parameters set the location of the center of the text, the origin mode can be set using the textMode() function. Text color can be changed with the fill() function.
If you need to get the dimensions of a string in the current style, see the textSize function documentation.
Syntax
text( string, x, y )
Parameters
Name | Description |
---|---|
string | the text string that you would like to draw onto the screen |
x | x-coordinate of the center of the text (this can be changed with textMode) |
y | y-coordinate of the center of the text (this can be changed with textMode) |
Related
line( x1, y1, x2, y2 )
Examples
function draw()
background(128)
stroke(255)
line(10, 10, 80, 80)
end
Description
Draws a line between the two points specified by x1,y1 and x2,y2. A line's color can be set with the stroke() function and its width can be set with the strokeWidth() function. A line's cap style can be changed with the lineCapMode() function. Note that line cap modes only take effect when drawing with the rendering mode set to smooth(). When using noSmooth(), lines will be rendered using square end caps.
Syntax
line( x1, y1, x2, y2 )
Parameters
Name | Description |
---|---|
x1 | x-coordinate of the first point |
y1 | y-coordinate of the first point |
x2 | x-coordinate of the second point |
y2 | y-coordinate of the second point |
Returns
None
Related
image
Examples
-- Create a 400x400 pixel image
myImage = image(400, 400)
-- Set a pixel
myImage:set(10,10,128,128,128,255)
-- Get a pixel
r,g,b,a = myImage:get(10,10)
Description
This type represents a 2D raster image, pixels can be set with image:set(x, y, color) and read with image:get(x, y). Images and sub-rectangles can be copied with image:copy(). Draw images onto the screen using sprite(image,x,y). See the relevant documentation pages for more details.You can access the width or the height of an image through its width and height properties.
The image.premultiplied flag allows you to specify whether the image was created with premultiplied alpha. Generally, for images you create yourself using image:set(), you'll want this set to false (the default). For images used with setContext() you will want this set to true. Note that using an image with setContext() will automatically set its premultiplied flag to true.
The constructor can alternatively take png or jpeg encoded binary data which it will decode and use to construct the image. Using this will enable premultiplied alpha, and the encoded data is assumed to be premultiplied.
Syntax
image( width, height )
image.width
image.height
image(data)
Parameters
Name | Description |
---|---|
width | integer, the width of the image in pixels |
height | integer, the height of the image in pixels |
premultiplied | boolean, tells Codea to render this image as a premultiplied image. The default is false. |
data | string, a sequence of bytes representing the encoded jpeg or png image data. |
Returns
The newly created image of given width and height
Related
image.get( x, y )
Examples
r,g,b,a = myImage:get( 15, 15 )
r,g,b = myImage:get( 25, 25 )
Description
This method returns the red, green, blue and alpha components of the pixel located at x, y in the image.
Syntax
image.get( x, y )
Parameters
Name | Description |
---|---|
x | integer, x location of the pixel to query |
y | integer, y location of the pixel to query |
Returns
Four values: red, green, blue and alpha representing the color of the pixel at x, y. The values are in the range 0 to 255.
Related
image.set( x, y, color )
Examples
myImage:set( 15, 15, color(20,30,40,255) )
myImage:set( 15, 15, 20, 30, 40, 255)
Description
This method sets the red, green, blue and alpha components of the pixel located at x, y. If no alpha parameter is given, it is assumed to be 255.
Syntax
image.set( x, y, color )
image.set( x, y, r, g, b, a)
image.set( x, y, r, g, b)
Parameters
Name | Description |
---|---|
x | integer, x location of the pixel to query. 1 is the left most column. Must be less than or equal to the image.width value. |
y | integer, y location of the pixel to query. 1 is the top most row. Must be less than or equal to the image.height value. |
color | color object, the color to set the pixel to |
r, g, b, a | integer, the red, green, blue and alpha value to set the pixel to. Between 0 and 255. |
Related
image.copy( x, y, w, h )
Examples
newImage = myImage:copy()
newImage = myImage:copy(20,40,100,100)
Description
This method will copy the pixels in one image into a new image. If no parameters are given, it will copy the whole image, otherwise it will copy the defined subregion. If the region is outside of the image, it will be adjusted to select a valid region from the image. If the rectangle is completely outside of the image, an error will occur.
Syntax
image:copy()
image:copy(x, y, width, height)
Parameters
Name | Description |
---|---|
x | integer, x location of the leftmost pixels of the copy region. |
y | integer, y location of the topmost pixels of the copy region |
width | positive integer, width in pixels of the copy region |
height | positive integer, height in pixels of the copy region |
Returns
The newly created image with a copy of the given image or a subregion of it.
Related
mesh
Examples
-- Create a mesh
myMesh = mesh()
-- Set vertices
myMesh.vertices = {vec3(0,0,0),
vec2(100,0,0),
vec3(50,100,0)}
-- Set all vertex colors to white
myMesh:setColors(255,255,255,255)
Description
This type represents a triangle mesh. Every three vertices draws a triangle. You can set vertices, texture coordinates and colors. You can also specify a texture using a sprite from a sprite pack or an image.
Syntax
m = mesh()
Parameters
Name | Description |
---|---|
vertices | table, an array of vec2 or vec3 objects |
colors | table, an array of color objects. If not set the global fill color is used for all vertices |
texCoords | table, an array of vec2 objects. If not set, triangles are drawn with color only |
texture | string or image, the texture to use when drawing this mesh. If not set, triangles are drawn with color only |
valid | bool, true if this mesh is valid for drawing |
size | int, number of vertices in this mesh |
Returns
The newly created empty mesh
Related
mesh.draw( m )
Description
This method draws the mesh object. The mesh object must be valid to be drawn. For a mesh to be valid it must have an equal number of vertices, colors, and texCoords (that are a multiple of three). With the exception that texCoords and / or colors may be nil
Syntax
myMesh:draw( m )
Parameters
Name | Description |
---|---|
m | the mesh to draw |
Related
mesh.setColors( c )
Description
This method draws the mesh object. The mesh object must be valid to be drawn. For a mesh to be valid it must have an equal number of vertices, colors, and texCoords (that are a multiple of three). With the exception that texCoords and / or colors may be nil
Syntax
myMesh:setColors( c )
myMesh:setColors( r, g, b )
myMesh:setColors( r, g, b, a )
Parameters
Name | Description |
---|---|
m | the mesh to draw |
Related
mesh.clear()
Description
This method clears a mesh removing all vertices, texCoords and colors. The underlying capacity of the mesh remain after clearing and this may be preferable to creating a new mesh
Syntax
myMesh:clear()
Related
mesh.addRect( x, y, w, h, r )
Description
This method appends a rectangle centered at the coordinates (x,y) with width, w and height, h. The optional parameter r specifies rotation in radians
Syntax
myMesh:addRect( x, y, w, h)
myMesh:addRect( x, y, w, h, r)
Parameters
Name | Description |
---|---|
x | float, the x coordinate used to place the rectangle |
y | float, the y coordinate used to place the rectangle |
y | float, the y coordinate used to place the rectangle |
w | float, the width of the rectangle |
h | float, the height of the rectangle |
r | float, the rotation of the rectangle |
Returns
Returns the index of this rectangle, which can be used to set its position later
Related
mesh.setRect( i, x, y, w, h, r )
Description
This method sets the geometry an existing rectangle with index i, centered at the coordinates (x,y) with width, w and height, h. The optional parameter r specifies rotation in radians
Syntax
myMesh:setRect( i, x, y, w, h)
myMesh:setRect( i, x, y, w, h, r)
Parameters
Name | Description |
---|---|
i | int, the index of the rectangle in the mesh |
x | float, the x coordinate used to place the rectangle |
y | float, the y coordinate used to place the rectangle |
y | float, the y coordinate used to place the rectangle |
w | float, the width of the rectangle |
h | float, the height of the rectangle |
r | float, the rotation of the rectangle |
Related
mesh.setRectTex( i, s, t, w, h )
Description
This method sets the texture coordinates of an existing rectangle with index i
Syntax
myMesh:setRect( i, s, t, w, h)
Parameters
Name | Description |
---|---|
i | int, the index of the rectangle in the mesh |
s | float, the left edge of the texture rectangle |
t | float, the bottom edge of the texture rectangle |
w | float, the width of the texture rectangle |
h | float, the height of the texture rectangle |
Related
mesh.setRectColor( i, r, g, b )
Description
This method sets the color of an existing rectangle with index i
Syntax
myMesh:setRectColor( i, c)
myMesh:setRectColor( i, r, g, b)
myMesh:setRectColor( i, r, g, b, a)
Parameters
Name | Description |
---|---|
i | int, the index of the rectangle in the mesh |
c | color, the color to set the rectangle to |
r | int, the red component of the color to use |
g | int, the green component of the color to use |
b | int, the blue component of the color to use |
a | int, the alpha component of the color to use |
Related
mesh.vertex( i )
Description
When called with one argument, i, this method returns the vertex at the index specified by i. When called with more arguments, this method sets the vertex at index i to the value provided by x, y, z or a vec3 or vec2.
This method is useful when you wish to set a single vertex, or small subset of vertices. It is much more efficient than assigning a new vertex table to the mesh.vertices property.
Syntax
myMesh:vertex( i )
myMesh:vertex( i, x, y, z )
myMesh:vertex( i, vec3 )
myMesh:vertex( i, x, y )
myMesh:vertex( i, vec2 )
Parameters
Name | Description |
---|---|
i | int, the index of the vertex in the mesh |
x | float, the x position to set vertex i to |
y | float, the y position to set vertex i to |
z | float, the z position to set vertex i to |
vec3 | vec3, the 3D position to set vertex i to |
vec2 | vec2, the 2D position to set vertex i to |
Returns
If called with one argument (the index of the vertex) then this returns a vec3 value representing the position of the vertex.
Related
mesh.texCoord( i )
Description
When called with one argument, i, this method returns the texture coordinate at the index specified by i. When called with more arguments, this method sets the texture coordinate at index i to the value provided by x, y or the given vec2 value.
This method is useful when you wish to set the texture coordinate of a single vertex, or small subset of vertices. It is much more efficient than assigning a new texture coordinate table to the mesh.texCoords property.
Syntax
myMesh:texCoord( i )
myMesh:texCoord( i, x, y )
myMesh:texCoord( i, vec2 )
Parameters
Name | Description |
---|---|
i | int, the index of the texture coordinate in the mesh |
x | float, the x value to set vertex i's texture coordinate to |
y | float, the y value to set vertex i's texture coordinate to |
vec2 | vec2, the texture coordinate value to set on vertex i |
Returns
If called with one argument (the index of the vertex) then this returns a vec2 value representing the texture coordinate at that vertex.
Related
mesh.color( i )
Description
When called with one argument, i, this method returns the color at the index specified by i. When called with more arguments, this method sets the color at index i to the value provided by r, g, b, a or the given color object.
This method is useful when you wish to set the color of a single vertex, or small subset of vertices. It is much more efficient than assigning a new color table to the mesh.colors property.
Syntax
myMesh:color( i )
myMesh:color( i, r, g, b )
myMesh:color( i, r, g, b, a )
myMesh:color( i, color )
Parameters
Name | Description |
---|---|
i | int, the index of the color in the mesh |
r | int, the red value to set vertex i's color to (0 to 255) |
g | int, the green value to set vertex i's color to (0 to 255) |
b | int, the blue value to set vertex i's color to (0 to 255) |
a | int, the alpha value to set vertex i's color to (0 to 255) |
color | color, the color to set vertex i to |
Returns
If called with one argument (the index of the vertex) then this returns a color object representing the color at that vertex.
Related
triangulate( points )
Description
Takes an array of points representing a polygon and decomposes it into a list of triangles
Syntax
triangleVertices = triangulate( points )
Parameters
Name | Description |
---|---|
points | table, an array of vec2 objects representing a polygon |
Returns
A triangle list generated from the supplied polygon in the form { t1p1, t1p2, t1p3, t2p1, t2p2, t2p3, ..., tNp3 }
Related
translate( x, y )
Description
Translates all subsequent drawing operations by the specified x and y values. Translations are cumulative, so a call to translate( 50, 0 ) followed by a call to translate( 10, 10 ) will translate all subsequent drawing operations by 60, 10. Translate can take an optional z parameter to specify depth.
Syntax
translate( x, y )
translate( x, y, z )
Parameters
Name | Description |
---|---|
x | amount of horizontal translation, in pixels |
y | amount of vertical translation, in pixels |
z | amount of depth translation, in pixels |
Related
rotate( angle )
Description
Specifies an amount of rotation (in degrees) to apply to all subsequent drawing. All subsequent drawing functions will be rotated by angle value specified in this function. Rotations are cumulative, so calling rotate(30) followed by rotate(20) has the same effect as rotate(50).
rotate() can also be called with a specific axis, defined by the x, y, z parameters. This allows rotation to occur on an arbitrary axis for 3D effects. By default the axis is (0, 0, 1), this means that objects rotate about the axis pointing toward the viewer.
Syntax
rotate( angle )
rotate( angle, x, y, z )
Parameters
Name | Description |
---|---|
angle | amount of rotation in degrees |
x | float, x value for the axis of rotation |
y | float, y value for the axis of rotation |
z | float, z value for the axis of rotation |
Related
scale( x, y )
Description
Specifies an amount of scale to apply to all drawing. All subsequent drawing functions will be scaled by the x and y values specified in this function. Scale values are specified as a scalar multipliers, for example, scale(2.0, 2.0) will double the x and y dimensions of subsequent drawing commands. scale() is cumulative, so calling scale(0.5) followed by scale(0.5) will scale all subsequent drawing operations by 0.25 (i.e., one quarter of their original size).
Syntax
scale( amount )
scale( x, y )
scale( x, y, z )
Parameters
Name | Description |
---|---|
amount | uniform amount of scale to apply horizontally and vertically. Applies on all axis, x, y and z. |
x | amount of scale to apply on the x axis (horizontal) |
y | amount of scale to apply on the y axis (vertical) |
z | amount of scale to apply on the z axis (depth) |
Related
zLevel( z )
Description
Sets the z level of future drawing operations. Negative values mean the drawing will occur behind (further into the screen), positive values will cause drawing to happen in front. By default all drawing will occur above previous drawing operations.
This property is pushed onto the matrix stack with pushMatrix()
Syntax
zLevel( z )
Parameters
Name | Description |
---|---|
z | float, the amount of depth for future drawing operations, use positive values to draw in front, and negative values to draw behind. |
Related
perspective( fov, aspect, near, far )
Description
Sets the projection matrix to the perspective projection defined by the parameters fov (field of view, in degrees), aspect (aspect ratio of the screen, defaults to WIDTH/HEIGHT), near and far. The near and far values specify the closest and farthest distance an object can be without being clipped by the view frustum.
When called without arguments, sets up a perspective projection with a field of view of 45 degrees and an aspect ratio of WIDTH/HEIGHT.
Syntax
perspective()
perspective( fov )
perspective( fov, aspect )
perspective( fov, aspect, near, far )
Parameters
Name | Description |
---|---|
fov | float, field of view in degrees |
aspect | float, aspect ratio of the screen. Defaults to WIDTH/HEIGHT |
near | float, near clipping plane, defaults to 0.1 |
far | float, far clipping plane, default value is computed based on the height of the screen |
Related
ortho( left, right, bottom, top )
Description
Sets the projection matrix to the orthographic projection defined by the parameters left, right, bottom, top, near and far. The near and far values specify the closest and farthest distance an object can be without being clipped by the view frustum.
When called with no arguments, sets up the default orthographic projection, equivalent to ortho( 0, WIDTH, 0, HEIGHT, -10, 10 ).
Syntax
ortho()
ortho( left, right, bottom, top )
ortho( left, right, bottom, top, near, far )
Parameters
Name | Description |
---|---|
left | float, left edge of the frustum |
right | float, right edge of the frustum |
bottom | float, bottom edge of the frustum |
top | float, top edge of the frustum |
Related
camera(eyeX,eyeY,eyeZ, cX,cY,cZ, upX,upY,upZ)
Description
Sets the view matrix to the simulate a camera positioned at eye and looking at center. With an up-vector specified by up.
This can be used in conjunction with the perspective projection to simulate a camera positioned in 3D space looking at your scene.
Syntax
camera( eyeX, eyeY, eyeZ,
centerX, centerY, centerZ,
upX, upY, upZ )
Parameters
Name | Description |
---|---|
eyeX/Y/Z | floats, position of the "eye" in 3D |
centerX/Y/Z | floats, coordinate to look at |
upX/Y/Z | floats, up-vector of the camera, defaults to (0, 1, 0) |
Related
applyMatrix( matrix )
Description
Multiplies the matrix specified by matrix against the current model matrix. The current model matrix represents the world transform, this is the same matrix used in pushMatrix and popMatrix operations.
Syntax
applyMatrix( matrix )
Parameters
Name | Description |
---|---|
matrix | matrix, the transformation to multiply against the current world transform |
Related
modelMatrix()
Description
When called with no arguments, returns a matrix containing current world transformation. When called with a matrix argument, sets the current world transformation to the given matrix.
Syntax
modelMatrix()
modelMatrix( matrix )
Parameters
Name | Description |
---|---|
matrix | matrix, the transformation to set as the current world transform |
Returns
The current model matrix when called with no arguments
Related
viewMatrix()
Description
When called with no arguments, returns a matrix containing current view transformation. When called with a matrix argument, sets the current view transformation to the given matrix.
The view transform defaults to the identity matrix and is provided as a convenient place to store a camera transform when dealing with 3D scenes. Standard Codea projects do not normally utilise it. See the camera() function for a convenient way to set up the view transform.
Syntax
viewMatrix()
viewMatrix( matrix )
Parameters
Name | Description |
---|---|
matrix | matrix, the transformation to set as the current view transform |
Returns
The current view matrix when called with no arguments
Related
projectionMatrix()
Description
When called with no arguments, returns a matrix containing current projection transformation. When called with a matrix argument, sets the current projection transformation to the given matrix.
The projection transform defaults to an orthographic projection the width and height of the screen. See the perspective and ortho functions for more advanced ways to set up the projection matrix.
Syntax
projectionMatrix()
projectionMatrix( matrix )
Parameters
Name | Description |
---|---|
matrix | matrix, the transformation to set as the current projection transform |
Returns
The current projection matrix when called with no arguments
Related
color
Examples
--Fill with red
c = color( 255, 0, 0 )
fill( c )
Description
This type represents a color with transparency information. You can provide this type as arguments to the style functions fill(), tint(), stroke(), and background().
Syntax
color.r
color.g
color.b
color.a
myColor = color( 255, 0, 0, 255 ) --red
Parameters
Name | Description |
---|---|
r | float, the red component of this color from 0 to 255 |
g | float, the green component of this color from 0 to 255 |
b | float, the blue component of this color from 0 to 255 |
a | float, the alpha component of this color from 0 to 255 |
Related
ellipseMode( MODE )
Description
Sets the origin of the ellipses drawn with the ellipse() function. The default is ellipseMode( CENTER ).
Syntax
ellipseMode()
ellipseMode( CENTER|RADIUS|CORNER|CORNERS )
Parameters
Name | Description |
---|---|
mode | either CENTER, RADIUS, CORNER or CORNERS |
CENTER x, y specifies the center of the ellipse, w, h specify its x and y diameter.
RADIUS x, y specifies the center of the ellipse, w, h specify its x and y radius.
CORNER x, y specifies the lower left corner of the ellipse, w, h specify the size its x and y diameter.
CORNERS x, y sets the lower left coordinate of the ellipse’s bounding box. w, h sets the upper right coordinate of the ellipse’s bounding box.|
Returns
The current ellipse mode if called without arguments. Returns nothing if called with arguments.
Related
rectMode( MODE )
Description
Sets the origin of the rectangles drawn with the rect() function. The default is rectMode( CORNER ).
Syntax
rectMode()
rectMode( CENTER|RADIUS|CORNER|CORNERS )
Parameters
Name | Description |
---|---|
mode | either CENTER, RADIUS, CORNER or CORNERS |
CENTER x, y specifies the center of the rectangle, w, h specifies the rectangle's width and height.
RADIUS x, y specifies the center of the rectangle, w, h specifies half the rectangle's width and height.
CORNER x, y specifies the lower left corner of the rectangle, w and h specify the rectangle's width and height.
CORNERS x, y sets the lower left coordinate of the rectangle's bounding box. w, h sets the upper right coordinate of the rectangle's bounding box.|
Returns
The current rect mode if called without arguments. Returns nothing if called with arguments.
Related
spriteMode( MODE )
Description
Sets the origin of the sprites drawn with the sprite() function. The default is spriteMode( CENTER ).
Syntax
spriteMode()
spriteMode( CENTER|RADIUS|CORNER|CORNERS )
Parameters
Name | Description |
---|---|
mode | either CENTER, RADIUS, CORNER or CORNERS |
CENTER x, y specifies the center of the sprite, w, h specifies the sprite's width and height.
RADIUS x, y specifies the center of the sprite, w, h specifies half the sprite's width and height.
CORNER x, y specifies the lower left corner of the sprite, w and h specify the sprite's width and height.
CORNERS x, y sets the lower left coordinate of the sprite's bounding box. w, h sets the upper right coordinate of the sprite's bounding box.|
Returns
The current sprite mode if called without arguments. Returns nothing if called with arguments.
Related
spriteSize( name )
Description
Returns the pixel size of the sprite specified by name. If the sprite name is valid this function returns two values, width and height.
Syntax
w, h = spriteSize("Planet Cute:Character Boy")
w, h = spriteSize( image )
Parameters
Name | Description |
---|---|
name | name of a sprite, in the form "Sprite Pack:Sprite Name" |
image | image object |
Returns
Width and height of the sprite specified by name, or image object
Related
textMode( MODE )
Description
Sets the origin of text drawn with the text() function. The default is textMode( CENTER ).
Syntax
textMode()
textMode( CENTER|CORNER )
Parameters
Name | Description |
---|---|
mode | either CENTER or CORNER |
CENTER x, y specifies the center of the text.
CORNER x, y specifies the lower left corner of the text.
Returns
The current text mode if called without arguments. Returns nothing if called with arguments.
Related
lineCapMode( MODE )
Examples
background(40, 40, 50)
smooth()
stroke(255)
strokeWidth(15)
translate(WIDTH/2, HEIGHT/2)
lineCapMode(ROUND)
line(-30, -30, -30, 30)
lineCapMode(SQUARE)
line(0, -30, 0, 30)
lineCapMode(PROJECT)
line(30, -30, 30, 30)
Description
Sets the style of the line caps drawn with the line() function. The default is lineCapMode( ROUND ). Note that lineCapMode() only has an effect if smooth() is set.
Syntax
lineCapMode()
lineCapMode( ROUND | SQUARE | PROJECT )
Parameters
Name | Description |
---|---|
mode | either ROUND, SQUARE or PROJECT |
ROUNDline ends are rounded with circles
SQUAREline ends are squared off at the end points
PROJECTline ends are squared off, but project out as far as if they were rounded
Returns
The current line cap mode if called without arguments. Returns nothing if called with arguments.
Related
fill( red, green, blue, alpha )
Description
Sets the color used to fill shapes drawn with the ellipse() and rect() functions. Also sets the color of text drawn with the text() function.
Syntax
fill()
fill( gray )
fill( gray, alpha )
fill( red, green, blue )
fill( red, green, blue, alpha )
fill( color )
Parameters
Name | Description |
---|---|
gray | int from 0 to 255, specifies value between white and black |
alpha | int from 0 to 255, specifies opacity of the fill |
red | int from 0 to 255, specifies red amount of the fill |
green | int from 0 to 255, specifies green amount of the fill |
blue | int from 0 to 255, specifies blue amount of the fill |
color | a value of the color datatype |
Returns
Four values (r,g,b,a) representing the current fill color if called without arguments. Returns nothing if called with arguments.
Related
noFill()
Description
Sets the color of the fill to completely transparent.
Syntax
noFill()
Related
tint( red, green, blue, alpha )
Examples
background(127, 127, 127, 255)
tint(255, 0, 0)
sprite("Planet Cute:Character Boy",
WIDTH / 2, HEIGHT / 2)
Description
Sets the color used to tint sprites drawn with the sprite() function. This color is multiplied with the sprite graphic's color by default.
Setting a white tint with a partial alpha value will make a sprite semi-transparent.
Syntax
tint()
tint( gray )
tint( gray, alpha )
tint( red, green, blue )
tint( red, green, blue, alpha )
tint( color )
Parameters
Name | Description |
---|---|
gray | int from 0 to 255, specifies value between white and black |
alpha | int from 0 to 255, specifies opacity of the tint |
red | int from 0 to 255, specifies red amount of the tint |
green | int from 0 to 255, specifies green amount of the tint |
blue | int from 0 to 255, specifies blue amount of the tint |
color | a value of the color datatype |
Returns
Four values (r,g,b,a) representing the current tint color if called without arguments. Returns nothing if called with arguments.
Related
noTint()
Description
Sets the color of the tint to white and completely opaque.
Syntax
noTint()
Related
stroke( red, green, blue, alpha )
Description
Sets the color used to outline the shapes drawn with the ellipse() and rect() functions. Also sets the color of lines drawn with the line() function.
Syntax
stroke()
stroke( gray )
stroke( gray, alpha )
stroke( red, green, blue )
stroke( red, green, blue, alpha )
stroke( color )
Parameters
Name | Description |
---|---|
gray | int from 0 to 255, specifies value between white and black |
alpha | int from 0 to 255, specifies opacity of the stroke |
red | int from 0 to 255, specifies red amount of the stroke |
green | int from 0 to 255, specifies green amount of the stroke |
blue | int from 0 to 255, specifies blue amount of the stroke |
color | a value of the color datatype |
Returns
Four values (r,g,b,a) representing the current stroke color if called without arguments. Returns nothing if called with arguments.
Related
strokeWidth( width )
Description
Sets the width of the outline of shapes drawn with the ellipse() and rect() functions. Also sets the width of lines drawn with the line() function.
Syntax
strokeWidth()
strokeWidth( width )
Parameters
Name | Description |
---|---|
width | int or float, the width in pixels of the stroke |
Returns
The current stroke width if called without arguments. Returns nothing if called with arguments.
Related
noStroke()
Description
Sets the stroke width to zero.
Syntax
noStroke()
Related
smooth()
Description
This enables smooth line drawing. Lines will appear anti-aliased and respect styles set using the lineCapMode() function.
Syntax
smooth()
Related
noSmooth()
Description
This disables smooth line drawing. Lines will appear aliased. Using this option allows you to draw very thin lines clearly.
Syntax
noSmooth()
Related
font( name )
Description
This sets the current font to the font specified by name. If no argument is given font() returns the current font. The default font is "Helvetica".
Syntax
font()
font( name )
Parameters
Name | Description |
---|---|
name | string, the name of the font to use. For iOS devices, this can be one of the following: |
AcademyEngravedLetPlain\nAmericanTypewriter-CondensedLight\nAmericanTypewriter-Light\nAmericanTypewriter\nAmericanTypewriter-Condensed\nAmericanTypewriter-Bold\nAmericanTypewriter-CondensedBold\nAppleColorEmoji\nAppleSDGothicNeo-Medium\nAppleSDGothicNeo-Bold\nArialMT\nArial-ItalicMT\nArial-BoldMT\nArial-BoldItalicMT\nArialHebrew\nArialHebrew-Bold\nBangalaSangamMN-Bold\nBangalaSangamMN\nBaskerville\nBaskerville-Italic\nBaskerville-SemiBold\nBaskerville-SemiBoldItalic\nBaskerville-Bold\nBaskerville-BoldItalic\nBodoniSvtyTwoITCTT-Book\nBodoniSvtyTwoITCTT-BookIta\nBodoniSvtyTwoITCTT-Bold\nBodoniSvtyTwoOSITCTT-Book\nBodoniSvtyTwoOSITCTT-BookIt\nBodoniSvtyTwoOSITCTT-Bold\nBodoniSvtyTwoSCITCTT-Book\nBodoniOrnamentsITCTT\nBradleyHandITCTT-Bold\nChalkboardSE-Light\nChalkboardSE-Regular\nChalkboardSE-Bold\nChalkduster\nCopperplate-Light\nCopperplate\nCopperplate-Bold\nCourier\nCourier-Oblique\nCourier-Bold\nCourier-BoldOblique\nCourierNewPSMT\nCourierNewPS-BoldMT\nCourierNewPS-BoldItalicMT\nCourierNewPS-ItalicMT\nDBLCDTempBlack\nDevanagariSangamMN\nDevanagariSangamMN-Bold\nDidot\nDidot-Italic\nDidot-Bold\nEuphemiaUCAS\nEuphemiaUCAS-Italic\nEuphemiaUCAS-Bold\nFutura-Medium\nFutura-MediumItalic\nFutura-CondensedMedium\nFutura-CondensedExtraBold\nGeezaPro\nGeezaPro-Bold\nGeorgia\nGeorgia-Italic\nGeorgia-Bold\nGeorgia-BoldItalic\nGillSans-Light\nGillSans-LightItalic\nGillSans\nGillSans-Italic\nGillSans-Bold\nGillSans-BoldItalic\nGujaratiSangamMN\nGujaratiSangamMN-Bold\nGurmukhiMN\nGurmukhiMN-Bold\nSTHeitiSC-Light\nSTHeitiSC-Medium\nSTHeitiTC-Light\nSTHeitiTC-Medium\nHelvetica-Light\nHelvetica-LightOblique\nHelvetica\nHelvetica-Oblique\nHelvetica-Bold\nHelvetica-BoldOblique\nHelveticaNeue-UltraLight\nHelveticaNeue-UltraLightItalic\nHelveticaNeue-Light\nHelveticaNeue-LightItalic\nHelveticaNeue\nHelveticaNeue-Italic\nHelveticaNeue-Medium\nHelveticaNeue-Bold\nHelveticaNeue-BoldItalic\nHelveticaNeue-CondensedBold\nHelveticaNeue-CondensedBlack\nHiraKakuProN-W3\nHiraKakuProN-W6\nHiraMinProN-W3\nHiraMinProN-W6\nHoeflerText-Regular\nHoeflerText-Italic\nHoeflerText-Black\nHoeflerText-BlackItalic\nKailasa\nKailasa-Bold\nKannadaSangamMN\nKannadaSangamMN-Bold\nMalayalamSangamMN\nMalayalamSangamMN-Bold\nMarion-Regular\nMarion-Italic\nMarion-Bold\nMarkerFelt-Thin\nMarkerFelt-Wide\nNoteworthy-Light\nNoteworthy-Bold\nOptima-Italic\nOptima-Regular\nOptima-Bold\nOptima-BoldItalic\nOptima-ExtraBlack\nOriyaSangamMN\nOriyaSangamMN-Bold\nPalatino-Roman\nPalatino-Italic\nPalatino-Bold\nPalatino-BoldItalic\nPapyrus\nPapyrus-Condensed\nPartyLetPlain\nSinhalaSangamMN\nSinhalaSangamMN-Bold\nSnellRoundhand\nSnellRoundhand-Bold\nSnellRoundhand-Black\nTamilSangamMN\nTamilSangamMN-Bold\nTeluguSangamMN\nTeluguSangamMN-Bold\nThonburi\nThonburi-Bold\nTimesNewRomanPSMT\nTimesNewRomanPS-ItalicMT\nTimesNewRomanPS-BoldMT\nTimesNewRomanPS-BoldItalicMT\nTrebuchetMS\nTrebuchetMS-Italic\nTrebuchetMS-Bold\nTrebuchetMS-BoldItalic\nVerdana\nVerdana-Italic\nVerdana-Bold\nVerdana-BoldItalic\nZapfDingbatsITC\nZapfino
Returns
The current font if called without arguments. Returns nothing if called with arguments.
Related
fontSize( size )
Description
This sets the current font size to the size specified by size. If no argument is given fontSize() returns the current font size. The default font size is 17 points.
Syntax
fontSize()
fontSize( size )
Parameters
Name | Description |
---|---|
size | float, the size of the font (in points). Must be greater than 0.0. |
Returns
The current font size if called without arguments. Returns nothing if called with arguments.
Related
fontMetrics()
Description
This function returns a table of font metrics for the currently defined font (as defined by font() and fontSize()). The metrics table contains advanced information about the font's measurements, such as ascent, leading, x height, and so on.
Please note that this function only works on iOS 5 and above.
Syntax
fontMetrics()
Returns
A table containing the following keys:
ascent
descent
leading
xHeight
capHeight
underlinePosition
underlineThickness
slantAngle
size
**
Related
textAlign( ALIGN )
Description
This sets the alignment of text rendered with the text() function. This is generally used in conjunction with textWrapWidth() to produce multi-line, word-wrapped text aligned to the LEFT, CENTER or RIGHT. If called without arguments this function returns the current text alignment. The default text alignment is textAlign( LEFT ).
Syntax
textAlign()
textAlign( LEFT|CENTER|RIGHT )
Parameters
Name | Description |
---|---|
ALIGN | Can be LEFT, CENTER or RIGHT |
Returns
The current text alignment if called without arguments. Returns nothing if called with arguments.
Related
textWrapWidth( width )
Examples
background(100, 120, 160)
font("Georgia")
fill(255)
fontSize(20)
textWrapWidth(70)
text("Hello World!", WIDTH/2, HEIGHT/2)
Description
This sets the wrap width, in pixels, of text rendered with text(). If set to a value greater than 0, it causes text to wrap onto the next line when the line's width exceeds the specified width. When this is called without arguments, it returns the current text wrap width. The default text wrap width is 0, which indicates no wrapping, and that text should be rendered on one line.
Syntax
textWrapWidth()
textWrapWidth( width )
Parameters
Name | Description |
---|---|
width | float, width before the text rendered by text() word-wraps |
Returns
The current text wrap width if called without arguments. Returns nothing if called with arguments.
Related
textSize( string )
Examples
background(100, 120, 160)
font("Georgia")
fontSize(20)
textWrapWidth(70)
-- Get the dimensions of our string
w,h = textSize("Hello World!")
-- Draw a box behind our text
fill(120,0,40)
strokeWidth(2)
rectMode(CENTER)
rect(WIDTH/2,HEIGHT/2,w+15,h+15)
fill(255)
text("Hello World!",WIDTH/2,HEIGHT/2)
Description
This function returns the dimensions of the specified string when rendered with the current font size and style. Note that this function returns two values: width and height. You can use these dimensions to, for example, render a button behind a piece of text, position text within a speech bubble, and so on.
Syntax
width = textSize( string )
width, height = textSize( string )
Parameters
Name | Description |
---|---|
string | string, the string to measure |
Returns
width and height of the text string when rendered with the current font size and style.
Related
pushMatrix()
Description
The pushMatrix() function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling popMatrix(). You can nest calls to pushMatrix() and popMatrix() for more complex object placement.
The following transform calls are preserved when using pushMatrix() and popMatrix(): translate(), rotate(), scale()
Syntax
pushMatrix()
Related
popMatrix()
Description
The pMatrix() function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling popMatrix(). You can nest calls to pushMatrix() and popMatrix() for more complex object placement.
The following transform calls are preserved when using pushMatrix() and popMatrix(): translate(), rotate(), scale()
Syntax
popMatrix()
Related
popMatrix()
Description
The pMatrix() function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling popMatrix(). You can nest calls to pushMatrix() and popMatrix() for more complex object placement.
The following transform calls are preserved when using pushMatrix() and popMatrix(): translate(), rotate(), scale()
Syntax
popMatrix()
Related
resetMatrix()
Description
This function resets all transformation. It replaces the current transform matrix with the identity matrix. This effectively repositions all drawing at 0, 0, with no rotation and scaling.
Syntax
resetMatrix()
Related
pushStyle()
Description
The pushStyle() function saves the current graphics style and pushes a copy of the current style onto the top of the stack. You can then modify the style, perform drawing operations, and return to the previous style by calling popStyle(). You can nest calls to pushStyle() and popStyle() in order to provide more control.
Styles set with the following functions are preserved when using pushStyle() and popStyle(): fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()
Syntax
pushStyle()
Related
popStyle()
Description
The pushStyle() function saves the current graphics style and pushes a copy of the current style onto the top of the stack. You can then modify the style, perform drawing operations, and return to the previous style by calling popStyle(). You can nest calls to pushStyle() and popStyle() in order to provide more control.
Styles set with the following functions are preserved when using pushStyle() and popStyle(): fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()
Syntax
popStyle()
Related
resetStyle()
Description
Calling resetStyle() will reset all style parameters to their default values. This will effect whatever style is currently on the top of the stack.
Styles set with the following functions are reset when using resetStyle(): fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()
Syntax
resetStyle()
Related
WIDTH
Description
This constant is set to the width of the screen in pixels.
Syntax
WIDTH
Returns
Width of the screen in pixels
Related
HEIGHT
Description
This constant is set to the height of the screen in pixels.
Syntax
HEIGHT
Returns
Height of the screen in pixels
Related
ElapsedTime
Description
Query this variable to get the current elapsed time, in seconds, while running your project.
Syntax
ElapsedTime
Returns
Time in seconds since the start of running the project
Related
DeltaTime
Description
Query this variable to get the time elapsed, in seconds, since the last draw call while running your project.
Syntax
DeltaTime
Returns
Time in seconds since the start of the previous frame
Related
ContentScaleFactor
Description
Query this variable to get the content scale factor. This specifies the internal scaling of images and sprites. On retina devices this will be equal to 2, on non-retina devices it will be equal to 1.
Syntax
ContentScaleFactor
Returns
Content scale factor of the viewer
Lua
Tables, Strings, Math and Time
For Loops Overview
Description
You can use for loops in Lua to iterate over arrays and tables, performing tasks for each element.
This example simply iterates i over the values 1 to 10
-- Iterate from 1 to 10
for i = 1, 10 do
print( i )
end
This example uses the ipairs function to sequentially iterate over a table. Note that ipairs only works on tables that have sequential elements beginning at 1.
-- Iterate over an array named 'arr'
arr = { 3, 2, 1 }
for i,v in ipairs(arr) do
print( "arr["..i.."] = "..v )
end
-- Prints:
-- arr[1] = 3
-- arr[2] = 2
-- arr[3] = 1
This example uses pairs to iterate over all the key/value pairs in a table, unlike ipairs the keys do not have to be integral values, and can be anything.
-- Iterate over a table named 'tab'
tab = { x = 3, y = "string", z = 1 }
for key,value in pairs(tab) do
print( "tab."..key.." = "..value )
end
-- Prints:
-- tab.y = string
-- tab.x = 3
-- tab.z = 1
Related
Conditionals Overview
Description
Use conditionals to test for a particular circumstance and then branch your code appropriately. See the examples below.
-- Check if x is equal to 10
if x == 10 then
print( "x equals 10" )
end
-- else and elseif
if x == 10 then
print( "x is 10" )
elseif x == 5 then
print( "x is 5" )
else
print( "x is something else: "..x )
end
-- Checking multiple values
if x == 10 and y < 5 then
print( "x is 10 and y is less than 5" )
elseif x == 5 or y == 3 then
print( "x is 5 or y is 3" )
else
print( "x is "..x.." and y is "..y )
end
ipairs( table )
Description
ipairs can be used to iterate over a table sequentially, starting from the index 1 and continuing until the first integer key absent from the table
Returns three values: an iterator function, the table, and 0.
Syntax
for i,v in ipairs( t ) do body end
-- This will iterate over the pairs:
-- (1,t[1]), (2,t[2]), ...
Parameters
Name | Description |
---|---|
table | table to iterate over |
Returns
Returns three values: an iterator function, the table, and 0
Related
pairs( table )
Description
pairs can be used to iterate over a table's key-value pairs.
Returns three values: the next function, the table t, and nil.
Syntax
for k,v in pairs( t ) do body end
-- This will iterate over all key-value
-- pairs in table t
Parameters
Name | Description |
---|---|
table | table to iterate over |
Returns
Returns three values: the next function, the table t, and nil
Related
table.concat( table, sep )
Description
Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ··· sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.
Syntax
table.concat( table )
table.concat( table, sep )
table.concat( table, sep, i )
table.concat( table, sep, i, j )
Parameters
Name | Description |
---|---|
table | table to concatenate |
sep | separator string |
i | int, starting index to concatenate from |
j | int, ending index |
Returns
A string of the elements in table concatenated with each other, separated by sep
table.insert( table, pos, value )
Description
Inserts element value at position pos in table, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of the table, so that a call table.insert(t,x) inserts x at the end of table t.
Syntax
table.insert( table, value )
table.insert( table, pos, value )
Parameters
Name | Description |
---|---|
table | table to insert into |
pos | int, position to inset |
value | value to insert |
Related
table.maxn( table )
Description
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)
Syntax
table.maxn( table )
Parameters
Name | Description |
---|---|
table | table to query |
Returns
Largest positive numerical index of the given table
table.remove( table, pos )
Description
Removes from table the element at position pos, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos is n, where n is the length of the table, so that a call table.remove(t) removes the last element of table t.
Syntax
table.remove( table )
table.remove( table, pos )
Parameters
Name | Description |
---|---|
table | table to insert into |
pos | int, position of value to remove |
Returns
Value of the removed element
Related
table.sort( table )
Description
Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.
The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.
Syntax
table.sort( table )
table.sort( table, comp )
Parameters
Name | Description |
---|---|
table | the table to sort |
comp | a function that receives two table elements and returns true when the first is less than the second |
os.clock()
Description
Returns an approximation of the amount in seconds of CPU time used by the program.
Syntax
os.clock()
Returns
Approximation of the amount in seconds of CPU time used by the program.
os.difftime( t2, t1 )
Description
Returns the number of seconds from time t1 to time t2. In POSIX, Windows, and some other systems, this value is exactly t2-t1.
Syntax
os.difftime( t2, t1 )
Parameters
Name | Description |
---|---|
t2 | Ending time |
t1 | Starting time |
Returns
Number of seconds from time t1 to time t2.
Related
os.date( format )
Description
Returns a string or a table containing the date and time, formatted according to the given string format.
If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value). Otherwise, date formats the current time.
If format starts with '!', then the date is formatted in Coordinated Universal Time. After this optional character, if format is the string '*t', then date returns a table with the following fields: year (four digits), month (1--12), day (1--31), hour (0--23), min (0--59), sec (0--61), wday (weekday, Sunday is 1), yday (day of the year), and isdst (daylight saving flag, a boolean).
If format is not '*t', then date returns the date as a string, formatted according to the same rules as the C function strftime.
When called without arguments, date returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.date() is equivalent to os.date('%c')).
Syntax
os.date()
os.date( format )
os.date( format, time )
Parameters
Name | Description |
---|---|
format | String used to format the returned date |
time | If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value). |
Returns
A string or a table containing the date and time.
Related
os.setlocale( locale )
Description
Sets the current locale of the program. locale is a string specifying a locale; category is an optional string describing which category to change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category is "all". The function returns the name of the new locale, or nil if the request cannot be honored.
If locale is the empty string, the current locale is set to an implementation-defined native locale. If locale is the string "C", the current locale is set to the standard C locale.
When called with nil as the first argument, this function only returns the name of the current locale for the given category.
Syntax
os.setlocale( locale )
os.setlocale( locale, category )
Parameters
Name | Description |
---|---|
locale | String specifying a locale, can be nil or the empty string. |
category | String specifying a category to set, can be "all", "collate", "ctype", "monetary", "numeric", or "time" |
Returns
When called with nil for the first argument, returns the name of the current locale for the given category.
Related
os.time()
Description
Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour, min, sec, and isdst (for a description of these fields, see the os.date function).
The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time can be used only as an argument to date and difftime.
Syntax
os.time()
os.time( table )
Parameters
Name | Description |
---|---|
table | This table must have fields year, month, and day, and may have fields hour, min, sec, and isdst |
Returns
A number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time can be used only as an argument to date and difftime.
Related
string.find( s, pattern )
Description
Looks for the first match of pattern in the string s. If it finds a match, then string.find() returns the indices of s where the occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search, its default value is 1 and can be negative. A value of true as the fourth optional argument plain turns off the pattern matching facilities so the function performs a plain "find substring" operation, with no characters in pattern being considered "magic." Note that if plain is given, then init must be given as well.
If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.
Syntax
string.find( s, pattern )
string.find( s, pattern, init )
string.find( s, pattern, init, plain )
Parameters
Name | Description |
---|---|
s | string to search in |
pattern | pattern to look for |
init | starting character in string to search from, default is 1 |
plain | boolean, perform a plain substring search |
Returns
The start and end indices of the match, or nil if no match. If the pattern has captures then captured values are also returned after the indices
string.format( formatstring, ... )
Examples
s = string.format("Number is %d", 5)
print( s )
-- prints "Number is 5"
Description
Returns a formatted version of its variable arguments following the description given in the first argument, which must be a string. The format string follows the same rules as the printf family of standard C functions. The only difference are that the options/modifiers *, 1, L, n, p and h are not supported and that there is an extra option q. The q option formats a string in a form suitable to be safely read back by the Lua interpreter, for example all double quotes, newlines, embedded zeros and backslashes will be escaped when written.
Syntax
string.format( formatstring, ... )
Parameters
Name | Description |
---|---|
formatstring | string defining the format |
Returns
A formatted string
string.len( s )
Description
Receives a string and returns its length. The empty string "" has length 0.
Syntax
string.len( s )
Parameters
Name | Description |
---|---|
s | get the length of this string |
Returns
Length of string s
string.lower( s )
Description
Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged.
Syntax
string.lower( s )
Parameters
Name | Description |
---|---|
s | get a lowercase version of this string |
Returns
Lowercase version of string s
Related
string.upper( s )
Description
Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged.
Syntax
string.upper( s )
Parameters
Name | Description |
---|---|
s | get an uppercase version of this string |
Returns
Uppercase version of string s
Related
string.match( s, pattern )
Description
Looks for the first match of pattern in the string s. If it finds one then string.match() returns the captures from the pattern, otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. A third optional numerical argument init specifies where to start the search. Its default is 1 and can be negative.
Syntax
string.match( s, pattern )
string.match( s, pattern, init )
Parameters
Name | Description |
---|---|
s | string to search |
pattern | pattern to match |
init | starting location in string |
Returns
Captures from the first match of pattern in string s, or nil if none were found
Related
string.rep( s, n )
Description
Returns a string that is the concatenation of n copies of the string s.
Syntax
string.rep( s, n )
Parameters
Name | Description |
---|---|
s | string to replicate |
n | int, number of times to replicate the string |
Returns
n concatenations of string s
string.sub( s, i, j )
Description
Returns the substring of s that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j) returns a prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i.
Syntax
string.sub( s, i )
string.sub( s, i, j )
Parameters
Name | Description |
---|---|
s | find substring of this string |
i | int, starting index |
j | int, ending index |
Returns
Substring of string s
math.abs( value )
Description
This function returns the absolute value of value. For example, math.abs(-5) returns 5.
Syntax
math.abs( value )
Parameters
Name | Description |
---|---|
value | int or float, the number to get the absolute value of |
Returns
The absolute value of value
math.acos( value )
Description
This function returns the arc cosine of value in radians
Syntax
math.acos( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the arc cosine of this number |
Returns
The arc cosine of value in radians
Related
math.asin( value )
Description
This function returns the arc sine of value in radians
Syntax
math.asin( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the arc sine of this number |
Returns
The arc sine of value in radians
Related
math.atan( value )
Description
This function returns the arc tangent of value in radians
Syntax
math.atan( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the arc tangent of this number |
Returns
The arc tangent of value in radians
Related
math.atan2( x, y )
Description
This function returns the arc tangent of y/x in radians, but uses the sign of both parameters to find the quadrant of the result. It also handles correctly the case of x being zero.
Syntax
math.atan2( x, y )
Parameters
Name | Description |
---|---|
x | int or float, denominator for arc tangent |
y | int or float, numerator for arc tangent |
Returns
The arc tangent of y/x in radians
Related
math.ceil( value )
Description
This function returns the smallest integer larger than or equal to value. This rounds a number up to the nearest integer. For example, math.ceil(5.2) returns 6.
Syntax
math.ceil( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the smallest integer larger than or equal to this number |
Returns
The smallest integer larger than or equal to value
Related
math.cos( value )
Description
This function returns the cosine of value (assumed to be in radians).
Syntax
math.cos( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the cosine of this number |
Returns
Cosine of value
Related
math.cosh( value )
Description
This function returns hyperbolic cosine of value.
Syntax
math.cosh( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the hyperbolic cosine of this number |
Returns
Hyperbolic cosine of value
Related
math.deg( value )
Description
This function returns the angle specified by value (given in radians) in degrees.
Syntax
math.deg( value )
Parameters
Name | Description |
---|---|
value | int or float, angle in radians to convert to degrees |
Returns
Angle specified by value (in radians) in degrees
Related
math.rad( value )
Description
This function returns the angle specified by value (given in degrees) in radians.
Syntax
math.rad( value )
Parameters
Name | Description |
---|---|
value | int or float, angle in degrees to convert to radians |
Returns
Angle specified by value (in degrees) in radians
Related
math.exp( value )
Description
This function returns e raised to value
Syntax
math.exp( value )
Parameters
Name | Description |
---|---|
value | int or float, exponent of e |
Returns
e raised to the power of value
math.floor( value )
Description
This function returns the largest integer smaller than or equal to value. This rounds a number down to the nearest integer. For example, math.floorTh(5.7) returns 5.
Syntax
math.floor( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the largest integer smaller than or equal to this number |
Returns
The largest integer smaller than or equal to value
Related
math.fmod( x, y )
Description
This function returns the remainder of the division of x by y that rounds the quotient towards zero.
Syntax
math.fmod( x, y )
Parameters
Name | Description |
---|---|
x | int or float |
y | int or float |
Returns
The remainder of the division of x by y
Related
math.frexp( value )
Description
This function returns m and e such that value = m2^e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).
Syntax
math.frexp( value )
Parameters
Name | Description |
---|---|
value | int or float |
Returns
m and e such that value = m2^e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).
Related
math.ldexp( m, e )
Description
This function returns m2^e (e should be an integer)
Syntax
math.ldexp( m, e )
Parameters
Name | Description |
---|---|
m | int or float |
m | int |
Returns
m2^e
Related
math.log( value )
Description
This function returns the natural logarithm of value
Syntax
math.log( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the natural logarithm of this value |
Returns
The natural logarithm of value
Related
math.log10( value )
Description
This function returns the base-10 logarithm of value
Syntax
math.log10( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the base-10 logarithm of this value |
Returns
The base-10 logarithm of value
Related
math.max( value, ... )
Description
This function returns maximum value among its arguments.
Syntax
math.max( value, ... )
Parameters
Name | Description |
---|---|
value | any comparable value |
Returns
The maximum value among its arguments
Related
math.min( value, ... )
Description
This function returns minimum value among its arguments.
Syntax
math.min( value, ... )
Parameters
Name | Description |
---|---|
value | any comparable value |
Returns
The minimum value among its arguments
Related
math.modf( value )
Description
This function returns two numbers, the integral part of value and the fractional part of value.
Syntax
math.modf( value )
Parameters
Name | Description |
---|---|
value | int or float |
Returns
Two numbers, the integral part of value and the fractional part of value
Related
math.pow( x, y )
Description
This function returns x raised to y. Equivalent to the expression x^y.
Syntax
math.pow( x, y )
Parameters
Name | Description |
---|---|
x | int or float |
y | int or float |
Returns
x raised to y
Related
math.random()
Description
When called without arguments, math.random() returns a uniform pseudo-random real number in the range [0, 1). When called with an integer number maximum, math.random() returns a uniform pseudo-random integer in the range [1, maximum]. When called with two integer numbers, minimum and maximum, math.random() returns a uniform pseudo-random integer in the range [minimum, maximum].
Syntax
math.random()
math.random( maximum )
math.random( minimum, maximum )
Parameters
Name | Description |
---|---|
minimum | int, minimum value of returned pseudo-random number |
maximum | int, maximum value of returned pseudo-random number |
Returns
A uniform pseudo-random real number or integer (depending on parameters)
Related
math.randomseed( value )
Description
Sets value as the "seed" for the pseudo-random number generator. Equal seeds produce equal sequences of numbers.
Syntax
math.randomseed( value )
Parameters
Name | Description |
---|---|
value | int, seed of the pseudo-random number generator |
Returns
A uniform pseudo-random real number or integer (depending on parameters)
Related
math.sin( value )
Description
This function returns the sine of value (assumed to be in radians).
Syntax
math.sin( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the sine of this number |
Returns
Sine of value
Related
math.sinh( value )
Description
This function returns hyperbolic sine of value.
Syntax
math.sinh( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the hyperbolic sine of this number |
Returns
Hyperbolic sine of value
Related
math.tan( value )
Description
This function returns the tangent of value (assumed to be in radians).
Syntax
math.tan( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the tangent of this number |
Returns
Tangent of value
Related
math.tanh( value )
Description
This function returns hyperbolic tangent of value.
Syntax
math.tanh( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the hyperbolic tangent of this number |
Returns
Hyperbolic tangent of value
Related
math.sqrt( value )
Description
This function computes the square root of value. You can also use the expression value^0.5 to compute this value.
Syntax
math.sqrt( value )
Parameters
Name | Description |
---|---|
value | int or float, compute the square root of this number |
Returns
Square root of value
Related
math.huge
Description
A value larger than or equal to any other numerical value.
Syntax
math.huge
Returns
A value larger than or equal to any other numerical value
math.pi
Description
The value of pi.
Syntax
math.pi
Returns
Value of pi
Touch
Detecting and Reacting to Touches on the Screen
CurrentTouch
Examples
function draw()
background( 0 )
fill( 255, 0, 0 )
ellipse( CurrentTouch.x, CurrentTouch.y, 300 )
end
Description
This global variable always represents the current single touch on the screen. It is a touch datatype, see the related items for more information.
Syntax
CurrentTouch
Related
touch
Description
This type represents data about a single touch on the screen.
Syntax
touch.id
touch.x
touch.y
touch.prevX
touch.prevY
touch.deltaX
touch.deltaY
touch.state
touch.tapCount
Parameters
Name | Description |
---|---|
id | int, a unique identifier for this touch |
x | float, specifies the x position of the touch on the screen |
y | float, specifies the y position of the touch on the screen |
prevX | float, specifies the x position, from the previous frame, of the touch on the screen |
prevY | float, specifies the y position, from the previous frame, of the touch on the screen |
deltaX | float, specifies the x delta since the last frame, the amount the touch has moved |
deltaY | float, specifies the y delta since the last frame, the amount the touch has moved |
state | the state of the touch, can be BEGAN, MOVING or ENDED |
tapCount | how many times the touch has been tapped |
Related
Parameters
Creating Parameters to Control Your Projects
parameter( name, min, max )
Examples
function setup()
--Creates a global variable called Radius
parameter("Radius", 50.0, 300.0, 100.0)
end
function draw()
background(128)
ellipseMode(RADIUS)
ellipse(WIDTH/2, HEIGHT/2, Radius)
end
Description
This function creates a visual slider in the viewer that can be used to adjust a global variable in your code.
You generally call the parameter() function in the setup() function of your main file. The string you specify for name will be exposed as a global variable that can be used in your code. When you adjust the slider in the viewer, the variable will be set appropriately. The last three parameters, min, max and initial allow you to set the minimum, maximum and initial value of your parameter respectively. If an initial value is not specified, then the parameter takes on the minimum value initially. If no minimum or maximum values are specified, the parameter uses the range [0, 1].
Syntax
parameter( name )
parameter( name, min, max )
parameter( name, min, max, initial )
Parameters
Name | Description |
---|---|
name | string, the parameter function will create a global variable with this name |
min | int or float, specifies the minimum value that your parameter can take |
max | int or float, specifies the maximum value that your parameter can take |
initial | int or float, specifies the initial, or starting, value of the parameter |
Related
iparameter( name, min, max )
Examples
function setup()
--Creates a global variable called Radius
parameter("Radius", 50, 300, 100)
end
function draw()
background(128)
ellipseMode(RADIUS)
ellipse(WIDTH/2, HEIGHT/2, Radius)
end
Description
This function creates a visual slider in the viewer that can be used to adjust a global variable in your code.
The main difference between this function and the parameter() function is that this function always sets the variable declared in name to an integer value. Thus its min, max and initial values must also be integers.
You generally call the iparameter() function in the setup() function of your main file. The string you specify for name will be exposed as a global variable that can be used in your code. When you adjust the slider in the viewer, the variable will be set appropriately. The last three parameters, min, max and initial allow you to set the minimum, maximum and initial value of your parameter respectively. If an initial value is not specified, then the parameter takes on the minimum value initially. If no minimum or maximum values are specified, the parameter uses the range [0, 10].
Syntax
iparameter( name )
iparameter( name, min, max )
iparameter( name, min, max, initial )
Parameters
Name | Description |
---|---|
name | string, the parameter function will create a global variable with this name |
min | int, specifies the minimum value that your parameter can take |
max | int, specifies the maximum value that your parameter can take |
initial | int, specifies the initial, or starting, value of the parameter |
Related
clearParameters()
Description
This function clears the parameter list of all parameter sliders and watch values. You can then re-add parameters using the parameter(), iparameter() and watch() functions.
Syntax
clearParameters()
Related
clearOutput()
Description
This function clears the output buffer for the print() function.
Syntax
clearOutput()
watch( name )
Examples
function setup()
--Shows the elapsed time in the viewer
watch("ElapsedTime")
end
Description
This function allows you to monitor the value of a Lua expression within the viewer. Generally you call the watch() function from the setup() function in your main file.
Syntax
watch( name )
Parameters
Name | Description |
---|---|
name | string, the global variable to watch |
Physics
Dynamic Motion with Forces, Joints and Collisions
physics.body
Examples
-- create a circle with 25px radius
circle = physics.body(CIRCLE, 25)
Description
This type represents a dynamic rigid body.
Syntax
myBody = physics.body( CIRCLE, radius )
myBody = physics.body( POLYGON,
vec2(-10,10),
vec2(-10,-10),
vec2(10,-10),
vec2(10,10)
myBody = physics.body( CHAIN, loop,
vec2(0,0),
vec2(10,5),
vec2(15,10) )
myBody = physics.body( EDGE, vec2(0,0),
vec2(10,10) )
Parameters
Name | Description |
---|---|
type | int, the type of the body, can be STATIC, DYNAMIC or KINEMATIC |
shapeType | readonly, the shape type of the body, can be CIRCLE, POLYGON, CHAIN or EDGE |
radius | float, the radius of the body, only valid for circle shape types |
points | table, a table containing the point that make up the body, only valid for polygon shape types |
x | float, the x position of the body in pixels |
y | float, the y position of the body in pixels |
position | vec2, the position of the body wrapped in a vector |
angle | float, the angle of the body in degrees |
linearVelocity | vec2, the current linear velocity of the body in pixels per second |
angularVelocity | float, the angular velocity of the body in degrees per second |
density | float, the density of the body in kg/m^2, 1 by default, cannot be negative |
mass | float, the mass of the body in kg, cannot be negative. If you set this, density will be ignored |
inertia | float, the momoment of inertia of the body. Cannot be set |
restitution | float, the restitution, or 'bouncyness' of the body |
friction | float, the friction of the body determines how easy the object slides |
fixedRotation | boolean, locks the rotation of this body |
active | boolean, set to false to remove from simulation |
awake | boolean, true if body is currently awake, false otherwise |
sleepingAllowed | boolean, set to false to prevent bodies from sleeping (default: true) |
bullet | boolean, set to true for fast moving bodies to prevent tunneling |
gravityScale | float, controls the influence of gravity on this body, 1 by default |
interpolate | boolean, controls render interpolation, used to smooth out motion but introduces slight lag |
info | value, used for storing arbitrary data in this body |
Related
CIRCLE
Description
This constant specifies the circle shape type.
Circle shapes are the fastest and simplest of the shape types, defined with a single parameter, radius.
Syntax
CIRCLE
Returns
int
Related
POLYGON
Description
This constant specifies the polygon shape type.
Polygon shapes are defined by a series of vertices. Non convex polygons are automatically decomposed into a set of convex polygons.
Syntax
POLYGON
Returns
int
Related
CHAIN
Description
This constant specifies the chain shape type.
Chain shapes are defined by a series of vertices that form an equivalent set of connected edges. This shape type has no mass and cannot be used in dynamic bodies.
Syntax
CHAIN
Returns
int
Related
EDGE
Description
This constant specifies the edge shape type.
Edge shapes are defined by two vertices, which form a straight line. This shape type has no mass and cannot be used in dynamic bodies.
Syntax
EDGE
Returns
int
Related
DYNAMIC
Description
This constant specifies the dynamic body type.
Dynamic bodies move under the influence of collisions, forces, joints and gravity.
Syntax
DYNAMIC
Returns
int
Related
STATIC
Description
This constant specifies the static body type.
Static bodies are unaffected by forces and collisions. They also do not collide with other static or kinematic bodies.
Also note that you cannot attach two static/kinematic bodies together with a joint.
Syntax
STATIC
Returns
int
Related
KINEMATIC
Description
This constant specifies the kinematic body type.
Kinematic bodies are unaffected by forces and collisions. Unlike static bodies, kinematic bodies are meant to be moved, usually by setting linear velocity directly. They also do not collide with other static or kinematic bodies.
Also note that you cannot attach two static/kinematic bodies together with a joint.
Syntax
KINEMATIC
Returns
int
Related
physics.joint
Description
This type represents a joint that constrains two rigid bodies together.
Syntax
physics.joint( REVOLUTE, bodyA, bodyB,
anchor )
physics.joint( PRISMATIC, bodyA, bodyB,
anchorA, anchorB )
physics.joint( DISTANCE, bodyA, bodyB,
anchorA, anchorB )
physics.joint( WELD, bodyA, bodyB,
anchor )
Parameters
Name | Description |
---|---|
type | int, the type of the joint, can be REVOLUTE, DISTANCE, PRISMATIC or WELD |
bodyA | body, the first body attached to this joint |
bodyB | body, the second body attached to this joint |
anchorA | vec2, the anchor for the first body in world coordinates |
anchorB | vec2, the anchor for the second body in world coordinates |
reactionForce | vec2, the current amount of force used by the joint to constrain the relative motion between the two bodies. This can be used to break joints when the force reaches a given threshold |
reactionTorque | float, the current amount of torque used by the joint to constrain the relative rotation between the two bodies. This can be used to break joints when the torque reaches a given threshold |
enableLimit | boolean, whether or not the limit for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have limits |
lowerLimit | float, the lower limit of this joint. For REVOLUTE joints this represents the angular limit between bodies in degrees. For PRISMATIC joints this represents the translation limit |
upperLimit | float, the upper limit of this joint. For REVOLUTE joints this represents the angular limit between bodies in degrees. For PRISMATIC joints this represents the translation limit |
enableMotor | boolean, whether or not the motor for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have motors |
motorSpeed | float, the desired speed of the motor. For REVOLUTE joints this is in degrees per second. For PRISMATIC joints this is specified in pixels per second |
maxMotorTorque | float, the maximum amount of torque the motor can apply to reach the desired motor speed. Only REVOLUTE joints have this property |
maxMotorForce | float, the maximum amount of force the motor can apply to reach the desired motor speed. Only PRISMATIC joints have this property |
length | float, the length of the joint. Only applies to DISTANCE joints |
frequency | float, The softness of the joint, set to zero for stiff joints. Only applies to DISTANCE and WELD joints |
dampingRatio | float, Controls the damping of soft joints, higher values reduce oscillation, set to zero for stiff joints. Only applies to DISTANCE and WELD joints |
Related
REVOLUTE
Description
This constant specifies the revolute joint type.
Revolute joints constrain two bodies so that they rotate about a single anchor point.
Syntax
REVOLUTE
Returns
int
Related
DISTANCE
Description
This constant specifies the distance joint type.
Distance joints constrain two bodies so that they maintain a fixed distance between their respective anchor points. The length of a distance joint is taken from the initial distance between the two anchor points in world space. Setting the frequency and damping ratio of the joint allows for soft spring-like behaviour.
Syntax
DISTANCE
Returns
int
Related
PRISMATIC
Description
This constant specifies the prismatic joint type.
Prismatic joints constrain the motion of two bodies along the axis between the two specified anchor points. This allows for telescopic motion, while restricting relative rotation between the two bodies.
Syntax
PRISMATIC
Returns
int
Related
WELD
Description
This constant specifies the weld joint type.
Weld joints constrain the motion and relative rotation between two bodies, effectively turning them into a single body. Due to the iterative nature of the solver, weld joints can bend when put under stress and may fail completely when large forces are involved or several weld joints are chained together to form a larger object.
Syntax
WELD
Returns
int
Related
Contacts Overview
Description
A contact occurs whenever two bodies collide with each other. Codea allows you to handle contacts by implementing a global function called collide( contact ) in your code.
-- This gets called whenever two bodies collide
function collide( contact )
if contact.state == BEGAN then
print("HIT!")
end
end
Contact objects contain information about the collision, such as the state, position of the collision, which bodies were involved, and so on. For a full listing of data available in a contact, see the physics.contact documentation.
Related
physics.contact
Examples
function collide(contact)
if contact.state == BEGAN
then print("HIT!")
end
end
Description
This type represents a collision between two bodies.
A physics.contact object is supplied to the global function collide( contact ) whenever a two bodies collide, maintain contact over multiple frames, or separate from each other. The contact supplied by this event will remain static as it is only a copy of the underlying physical state.
Syntax
Parameters
Name | Description |
---|---|
id | number, a unique id that represents this contact |
state | int, the current state of this contact, can be BEGAN, PERSIST, ENDED |
touching | bool, whether or not the contact is currently touching. Due to the way contacts are cached this can be false under some circumstances. |
position | vec2, the current position of this contact |
normal | vec2, the current normal of this contact |
normalImpulse | float, the magnitude of energy used to separate the two colliding bodies projected along the normal vector. Useful for measuring the strength of an impact |
normalImpulse | float, the magnitude of energy used to separate the two colliding bodies projected along the tangent vector (perpendicular to the normal). Useful for measuring the friction of an impact |
pointCount | int, the number of points in the contact manifold |
points | table, an array of vec2's describing the contact manifold |
bodyA | body, the first body in the collision represented by this contact |
bodyB | body, the second body in the collision represented by this contact |
Related
body.applyForce( force )
Description
Applies a force to this body object.
Syntax
myBody:applyForce( force )
myBody:applyForce( force, worldPoint )
Parameters
Name | Description |
---|---|
force | vec2, the amount of force to apply as a vector |
worldPoint | vec2, the point to apply the force from, in world coordinates |
Related
body.applyTorque( torque )
Description
Applies torque to this body object.
Syntax
myBody:applyTorque( applyTorque )
Parameters
Name | Description |
---|---|
torque | float, the amount of torque |
Related
body.destroy()
Examples
-- destroy should be used before
-- setting a body to nil
circle = physics.body(CIRCLE, 100)
circle:destroy()
circle = nil
Description
A body will be removed from the simulation automatically when garbage collected, however this may not happen immediately. To ensure that a body is removed from the simulation, use destroy(). Please note that all methods and properties will cease to work after destroy() is called.
Syntax
myBody:destroy()
Related
body.testPoint( worldPoint )
Examples
-- test if CurrentTouch is inside this body
circle = physics.body(CIRCLE, 100)
point = vec2(CurrentTouch.x, CurrentTouch.y)
if circle:testPoint(point) then print("HIT!") end
Description
Tests if worldPoint is inside this body.
Syntax
testPoint( worldPoint )
Parameters
Name | Description |
---|---|
worldPoint | vec2, the point to test for intersection, in world space |
Returns
true if worldPoint is inside this body, false otherwise
Related
body.testOverlap( otherBody )
Examples
-- test if two bodies overlap
circle1 = physics.body(CIRCLE, 100)
circle2 = physics.body(CIRCLE, 10)
if circle1:testOverlap(circle2)
then print("HIT!")
end
Description
Tests if this body intersects with otherBody.
This is useful if you want to do simple shape intersection tests that do not require realtime contact information.
Syntax
testOverlap( otherBody )
Parameters
Name | Description |
---|---|
otherBody | body, the body to test for intersection with |
Returns
true if this body is intersecting with otherBody, false otherwise
Related
body.getLocalPoint( worldPoint )
Examples
-- TODO example
Description
Converts a point to the local coordinate space of this body
Syntax
myBody:getLocalPoint( worldPoint )
Returns
vec2, coordinate in local space of this body
Related
body.getWorldPoint( localPoint )
Examples
-- TODO example
Description
Converts a point from the local coordinate space of this body to world space
Syntax
myBody:getWorldPoint( localPoint )
Returns
vec2, coordinate in world space
Related
body.getLinearVelocityFromWorldPoint( point )
Examples
-- TODO example
Description
Samples the linear velocity of this body at a given point in world space.
Syntax
myBody:getLinearVelocityFromWorldPoint( worldPoint )
Returns
vec2, linear velocity at worldPoint of this body
Related
body.getLinearVelocityFromLocalPoint( point )
Examples
-- TODO example
Description
Samples the linear velocity of this body at a given point in local space.
Syntax
myBody:getLinearVelocityFromLocalPoint( worldPoint )
Returns
vec2, linear velocity at localPoint of this body
Related
physics.pause()
Description
Pauses the physics simulation.
Syntax
-- pause physics
physics.pause()
Related
physics.resume()
Description
Resumes the physics simulation.
Syntax
-- resume physics
physics.resume()
Related
physics.raycast( start, end, ... )
Description
Performs a raycast from the start point to the end point.
Any additional parameters are treated as category filters, allowing certain bodies to be ignored. This function only returns hit information on the closest rigid body detected.
Syntax
physics.raycast(start, end)
physics.raycast(start, end, category1)
physics.raycast(start, end, category1, category2)
Parameters
Name | Description |
---|---|
start | vec2, the start point of the ray (technically a line segment, but finite for practical purposes) |
end | vec2, the end point of the ray |
Returns
table, if the raycast intersects a body this function will return a table containing the following key-value pairs
body => detected body
point => point of intersection
normal => normal on surface of hit body
fraction => fraction of total ray length from start to intersecton point
Related
physics.raycastAll( start, end, ... )
Description
Performs a raycast from the start point to the end point.
Any additional parameters are treated as category filters, allowing certain bodies to be ignored. This function returns an array of tables describing all objects hit along the ray, ordered from closest to farthest.
Syntax
physics.raycastAll(start, end)
physics.raycastAll(start, end, category1)
physics.raycastAll(start, end, category1, category2)
Parameters
Name | Description |
---|---|
start | vec2, the start point of the ray (technically a line segment, but finite for practical purposes) |
end | vec2, the end point of the ray |
Returns
array, if the raycast intersects one or more bodies this function will an array of tables containing the following key-value pairs
body => detected body
point => point of intersection
normal => normal on surface of hit body
fraction => fraction of total ray length from start to intersecton point
Related
physics.queryAABB( lowerLeft, upperRight, ... )
Description
Performs a query to find all bodies within the supplied axis-aligned bounding box.
Any additional parameters are treated as category filters, allowing certain bodies to be ignored.
Syntax
physics.queryAABB(lowerLeft, upperRight)
physics.queryAABB(lowerLeft, upperRight, category1)
physics.queryAABB(lowerLeft, upperRight,
category1, category2)
Parameters
Name | Description |
---|---|
lowerLeft | vec2, the position of the lower left corner of the query axis-aligned bounding box |
upperRight | vec2, the position of the upper right corner of the query axis-aligned bounding box |
Returns
array, returns all bodies that lie within the supplied bounding box
Related
physics.gravity( x, y )
Description
Sets the gravity of the world, units are in pixels per second^2. Use the Gravity global to set to device gravity. When no parameters are passed, function returns current world gravity as a vec2.
Syntax
physics.gravity( x, y )
physics.gravity( grav )
physics.gravity( Gravity )
Parameters
Name | Description |
---|---|
x | float, gravity in the x-axis |
y | float, gravity in the y-axis |
grav | vec2, gravity in both axes |
Gravity | vec3, device gravity used as a special case |
Returns
vec2, the current world gravity if no parameters are supplied
Related
physics.iterations( velIterations, posIterations )
Description
Sets the iterations used by the physics solver. Larger iterations tend to result in more stable physics, but will slow down the simulation.
Syntax
physics.iterations( velocityIterations,
positionIterations )
Parameters
Name | Description |
---|---|
velocityIterations | int, the number of velocity iterations performed each time step (default: 10) |
positionIterations | int, the number of position iterations performed each time step (default: 8) |
Related
physics.pixelToMeterRatio( ptmRatio )
Description
Sets the ratio between pixels and meters in the simulation.
This is used to make objects on the screen appear at a reasonable scale, while allowing the physics engine to remain stable. The default value is 32, meaning that for every 32 pixels in screen space there is 1 meter in physics space. This can be largely ignored in most cases, however if dealing with objects much larger or smaller than the default settings, it can be useful to change the ratio to something closer to that scale. Passing no parameters will cause this function to return the current ratio.
Syntax
physics.pixelToMeterRatio( ptmRatio )
physics.pixelToMeterRatio()
Parameters
Name | Description |
---|---|
ptmRatio | int, the number of pixels per meter (default: 32) |
Returns
int, the current ratio (when no parameters are supplied)
Related
Sounds
Playing and Generating Sound Effects
sound( name, seed )
Examples
-- using a string
sound( "jump", 1234 )
-- using the predefined constant
sound( SOUND_JUMP, 1234 )
-- using the table to define properties
sound( { Waveform = SOUND_NOISE,
AttackTime = 1.2,
SustainTime = 1 } )
Description
Calling this function immediately plays either a randomly generated sound with a type specified by name or using the given parameters.
sound() uses sfxr to randomly generate sounds of a given type. The name parameter is a string specifying the type of sound (see related items), and the seed parameter allows you to choose a particular random sound. Sounds with the same name and seed always sound the same. If no seed is specified the resulting sound will be a random sound of the specified type. If a parameter_table is passed in, those values are used to generate the sound.
Syntax
sound( name )
sound( name, seed )
sound( parameter_table )
sound( buffer )
Parameters
Name | Description |
---|---|
name | string, the type of sound to play |
can be "blit", "explode", "hit", "jump", "pickup", "powerup", "random" or "shoot". Can also be "data" followed by a base64 string encoding the parameters which is generated by Codea based on the sound picker panel properties and should not be edited|
seed | int, specifies the random seed to use when generating a sound of this type |
buffer | soundbuffer, specifies the raw sound data to play |
parameter_table | table, specifies the parameters to use when generating a sound. This is an advanced option, the parameters will change the noise in subtle ways. Play with the Sounds Plus example app to see what these parameters do. Any missing keys will cause the sound to use a default value for that parameter |
The table can contain the following (case sensitive) keys:
Waveform - The synthesizer waveform to use, can be SOUND_NOISE, SOUND_SAWTOOTH, SOUND_SINEWAVE, or SOUND_SQUAREWAVE
AttackTime - number
SustainTime - number
SustainPunch - number
DecayTime - number
StartFrequency - number
MinimumFrequency - number
Slide - number
DeltaSlide - number
VibratoDepth - number
VibratoSpeed - number
ChangeAmount - number
ChangeSpeed - number
SquareDuty - number
DutySweep - number
RepeatSpeed - number
PhaserSweep - number
LowPassFilterCutoff - number
LowPassFilterCutoffSweep - number
LowPassFilterResonance - number
HighPassFilterCutoff - number
HighPassFilterCutoffSweep - number
Volume - number
Related
- SOUND_BLIT
- SOUND_EXPLODE
- SOUND_HIT
- SOUND_JUMP
- SOUND_PICKUP
- SOUND_POWERUP
- SOUND_RANDOM
- SOUND_SHOOT
- SOUND_NOISE
- sound buffer
- SOUND_SQUAREWAVE
- SOUND_SINEWAVE
- SOUND_SAWTOOTH
soundbuffer( data, format, freq )
Examples
-- Creating a sound buffer object
function setup()
tap = false
iparameter("freq",1,4000,800)
parameter("length",0.1,1,0.5)
end
function makeBuffer()
local data = ""
datum="\0\255"
numSamples = freq * length
for i = 1,numSamples/#datum do
data = data .. datum
end
return sound buffer( data, FORMAT_MONO8, freq )
end
function touched(touch)
if touch.state == ENDED and
touch.tapCount == 1 then
tap = true
end
end
function draw()
background(0)
if tap then
b = makeBuffer()
sound(b)
tap = false
end
end
Description
This object represents a sound buffer containing arbitrary audio data. You may create soundbuffer objects using soundbuffer( data, format, freq ) where the data is uncompressed PCM audio and the format is one of FORMAT_MONO8, FORMAT_MONO16, FORMAT_STEREO8, or FORMAT_STEREO16.
Syntax
soundbuffer( data, format, freq )
Parameters
Name | Description |
---|---|
data | string, uncompressed audio data |
format | FORMAT_MONO8, FORMAT_MONO16, FORMAT_STEREO8 or FORMAT_STEREO16 |
freq | integer, the frequency of the data |
Returns
A new soundbuffer object
Related
soundBufferSize( size )
Examples
-- setting the sound buffer maximum size
soundBufferSize( 3 )
-- reading the current maximum size and used size
maxSize, usedSize = nsoundBufferSize()
-- setting to no limit
soundBufferSize(0)
Description
Calling this function will set the maximum buffer size for sounds. Sounds are stored in a buffer so that they do not need to be recreated if reused. Sounds are removed from this buffer on a least recently used basis when the buffer is full and a new sound is added. For example, if the buffer is 2 megabytes (the default), and we add a sound that puts it over the limit, the sound we used the longest time ago is removed from the buffer and will have to be re-created if played again. Generating the sound data can take a considerable amount of time for longer sounds.
Playing a sound at 0 volume counts as playing and can be used to keep a sound in the cache (and to pre-generate a sound in the setup function.)
Calling this method with 0 for the size sets the buffer to no limit. This can cause Codea to crash if too many sounds are generated as it may run out of memory.
Calling this with no parameters returns the max size and current size of the buffer.
Syntax
soundBufferSize( size )
soundBufferSize()
Parameters
Name | Description |
---|---|
size | number, the maximum size of the buffer in megabytes. This can be a fraction. If this is 0, the buffer size is unlimited. An unlimited buffer size can cause Codea to crash if it runs out of memory, so take care if it is used. |
Returns
If no parameters are given, a pair of values: maxBufferSize, currentBufferSize
Related
SOUND_JUMP
Description
This constant specifies a jump sound. Similar to a character jumping in a platform game.
Syntax
SOUND_JUMP
Returns
The string "jump"
Related
SOUND_HIT
Description
This constant specifies a hit sound. For example, when the enemy collides with the player.
Syntax
SOUND_HIT
Returns
The string "hit"
Related
SOUND_PICKUP
Description
This constant specifies a pickup sound. For example, collecting coins in a game.
Syntax
SOUND_PICKUP
Returns
The string "pickup"
Related
SOUND_POWERUP
Description
This constant specifies a powerup sound. For example, collecting bonuses in a game.
Syntax
SOUND_POWERUP
Returns
The string "powerup"
Related
SOUND_SHOOT
Description
This constant specifies a shooting sound. For example, firing a bullet in a game.
Syntax
SOUND_SHOOT
Returns
The string "shoot"
Related
SOUND_EXPLODE
Description
This constant specifies an explosion sound. For example, a space ship blowing up.
Syntax
SOUND_EXPLODE
Returns
The string "explode"
Related
SOUND_BLIT
Description
This constant specifies a generic "blit" sound.
Syntax
SOUND_BLIT
Returns
The string "blit"
Related
SOUND_RANDOM
Description
This constant specifies a randomly generated sound. You can use this in conjunction with the seed value of the sound() function to find a sound that you like.
Syntax
SOUND_RANDOM
Returns
The string "random"
Related
SOUND_NOISE
Description
This specifices to use a white noise function as the waveform for this sound
Syntax
SOUND_NOISE
Returns
The integer 3
Related
SOUND_SAWTOOTH
Description
This specifices to use a sawtooth function as the waveform for this sound
Syntax
SOUND_SAWTOOTH
Returns
The integer 1
Related
SOUND_SINEWAVE
Description
This specifices to use a sine wave function as the waveform for this sound
Syntax
SOUND_SINEWAVE
Returns
The integer 2
Related
SOUND_SQUAREWAVE
Description
This specifices to use a square wave function as the waveform for this sound
Syntax
SOUND_SQUAREWAVE
Returns
The integer 0
Related
Display & Keyboard
Using the Viewer's Display Modes
displayMode( MODE )
Examples
function setup()
--Set the viewer to fullscreen
displayMode( FULLSCREEN )
end
function setup()
--Set the viewer to standard
--i.e. visible parameters and output
displayMode( STANDARD )
end
function setup()
--Set the viewer to fullscreen
--Hide back/pause/play buttons
displayMode( FULLSCREEN_NO_BUTTONS )
end
Description
Changes the display mode of the viewer. You can use this to render your games and simulations in fullscreen mode, fullscreen mode without buttons, or standard mode
Syntax
displayMode( STANDARD |
FULLSCREEN |
FULLSCREEN_NO_BUTTONS )
Parameters
Name | Description |
---|---|
mode | Either STANDARD, FULLSCREEN or FULLSCREEN_NO_BUTTONS |
Related
FULLSCREEN
Description
Use this value in displayMode() to set the viewer to fullscreen mode. The Back, Pause, Play and Reset buttons will still be visible in the lower left corner of the screen.
Syntax
FULLSCREEN
Related
STANDARD
Description
Use this value in displayMode() or backingMode()
When used with displayMode() this sets the viewer to standard screen mode. You will be able to see the output and parameters panes to the left of the viewer, and the Back, Pause, Play and Reset buttons will be visible in the lower left corner of the screen.
When used with backingMode() this tells the viewer to render without using a retained backing, this means that the contents of the previous frame are not guaranteed to be preserved when entering the draw() call. This offers the best drawing performance.
Syntax
displayMode( STANDARD )
backingMode( STANDARD )
Related
FULLSCREEN_NO_BUTTONS
Description
Use this value in displayMode() to set the viewer to fullscreen mode and hide all buttons on the screen. Note: you will not be able to exit the viewer unless you implement your own call to the close() function. You can force the standard Back button to appear by triple-tapping the screen with three fingers.
Syntax
FULLSCREEN_NO_BUTTONS
Related
Orientation Overview
Examples
supportedOrientations(ANY)
function setup()
--Any orientation supported (default)
end
function orientationChanged( newOrientation )
-- This function gets called when
-- the device orientation changes
end
Description
Codea allows your projects to run in any orientation your device supports. However, you can limit supported orientations by using the supportedOrientations() function. You might want to do this if you only want your project to run in landscape mode, or if you want to make use of the accelerometer and do not want the user to inadvertently rotate the screen.
When the device orientation changes, Codea calls the global function orientationChanged( orientation ) and passes it the new orientation.
Related
CurrentOrientation
Description
This global contains the current orientation and can be one of the following: PORTRAIT, PORTRAIT_UPSIDE_DOWN, LANDSCAPE_LEFT, LANDSCAPE_RIGHT.
Related
supportedOrientations( ORIENTATION, ... )
Examples
supportedOrientations(PORTRAIT_ANY)
function setup()
--Only support portrait orientations
end
supportedOrientations(LANDSCAPE_LEFT)
function setup()
--Only support landscape left orientation
end
Description
Use this function to tell Codea which orientations the viewer should support for your project. This function accepts a variable number of arguments, each one specifying an orientation you wish to support. If you call this function with no arguments it will return all the currently supported orientations.
Note that while you are allowed to call this function from within your setup() function, it is recommended that you call this function from outside your setup() function, as indicated by the above examples. This is because by the time setup() is executed the viewer has already assumed an orientation and will only lock into a new orientation once the device is rotated. If called in the global scope the viewer will be configured in advance to support the orientation(s) you desire.
Syntax
supportedOrientations()
supportedOrientations( orient1, orient2, … )
Parameters
Name | Description |
---|---|
orientation | Can be one of the following values: |
ANY
PORTRAIT
PORTRAIT_UPSIDE_DOWN
PORTRAIT_ANY
LANDSCAPE_LEFT
LANDSCAPE_RIGHT
LANDSCAPE_ANY
Returns
All the currently supported orientations if called with no arguments. Otherwise this function returns nothing.
Related
ANY
Description
Use this value in supportedOrientation() to allow the viewer to assume any orientation when the device is rotated.
Syntax
supportedOrientation( ANY )
Related
PORTRAIT_ANY
Description
Use this value in supportedOrientation() to allow the viewer to assume either of the two portrait orientations (PORTRAIT, PORTRAIT_UPSIDE_DOWN) when the device is rotated.
Syntax
supportedOrientation( PORTRAIT_ANY )
Related
PORTRAIT
Description
Use this value in supportedOrientation() to allow the viewer to assume the standard portrait orientation (home button at the bottom).
Syntax
supportedOrientation( PORTRAIT )
Related
PORTRAIT_UPSIDE_DOWN
Description
Use this value in supportedOrientation() to allow the viewer to assume an inverted portrait orientation (home button at the top).
Syntax
supportedOrientation( PORTRAIT_UPSIDE_DOWN )
Related
LANDSCAPE_ANY
Description
Use this value in supportedOrientation() to allow the viewer to assume either of the two landscape orientations (LANDSCAPE_LEFT, LANDSCAPE_RIGHT) when the device is rotated.
Syntax
supportedOrientation( LANDSCAPE_ANY )
Related
LANDSCAPE_LEFT
Description
Use this value in supportedOrientation() to allow the viewer to assume the landscape left orientation (home button on left).
Syntax
supportedOrientation( LANDSCAPE_LEFT )
Related
LANDSCAPE_RIGHT
Description
Use this value in supportedOrientation() to allow the viewer to assume the landscape right orientation (home button on right).
Syntax
supportedOrientation( LANDSCAPE_RIGHT )
Related
Using the Keyboard
Description
You can use the keyboard in Codea to receive text input in your projects. In order to begin receiving keyboard events, call the showKeyboard() function. This will show the on-screen keyboard, unless an external keyboard is present. When key presses are made Codea calls the global function keyboard( key ). You must implement this function to receive keyboard events.
function keyboard( key )
print("Key pressed: '".. key .."'")
end
Alternatively you can read the current keyboard buffer by calling keyboardBuffer(). See the keyboardBuffer() documentation for an example.
Related
showKeyboard()
Examples
function touched(touch)
--Show keyboard when the screen is touched
showKeyboard()
end
Description
This function enables keyboard input and displays the software keyboard if necessary. After calling showKeyboard(), keyboard events will be delivered to a global function keyboard( key ). The current keyboard buffer can be read with the keyboardBuffer() function.
Syntax
showKeyboard()
Related
hideKeyboard()
Description
This function disables keyboard input and hides the software keyboard if necessary.
Syntax
hideKeyboard()
Related
keyboardBuffer()
Examples
function touched(touch)
--Show keyboard when the screen is touched
showKeyboard()
end
function draw()
background(40,40,50)
fill(255)
textMode(CORNER)
buffer = keyboardBuffer()
_,bufferHeight = textSize(buffer)
if buffer then
text( buffer, 10,
HEIGHT - 30 - bufferHeight )
end
end
Description
This function reads the current keyboard buffer. Note that the keyboard buffer is cleared when the keyboard is shown.
Syntax
buffer = keyboardBuffer()
Returns
Contents of keyboard buffer as a string
Related
BACKSPACE
Examples
function keyboard(key)
-- Did the user press backspace?
if key == BACKSPACE then
-- Do something
end
end
Description
You can use this to check whether the key delivered to the global keyboard( key ) function was the backspace key..
Syntax
BACKSPACE
Related
startRecording()
Description
This function initiates the video recording feature of Codea. To stop video recording use the stopRecording() function. This function is identical to pressing the video record button in the viewer interface. Do not call this function in your setup() function.
Syntax
startRecording()
Related
stopRecording()
Description
Use this function to stop Codea's video recording feature and save the recorded video to the device's camera roll.
Syntax
stopRecording()
Related
isRecording()
Description
Use this function to programatically determine whether Codea is currently recording the screen.
Syntax
isRecording()
Returns
Boolean, whether Codea is recording the screen
Related
backingMode( MODE )
Examples
function setup()
--Use a standard backing mode (default)
backingMode( STANDARD )
end
function setup()
--Use a retained backing mode
backingMode( RETAINED )
end
Description
Changes the backing mode of the viewer. The default, STANDARD, is the fastest drawing mode and may not preserve the contents of the previously drawn frame when setting up next frame.
Use the RETAINED backing mode to force the viewer to copy the contents of the previous frame into the current frame each time draw() is called. This is useful for projects that need to paint onto the screen and preserve the screen's contents, for example, painting or drawing applications.
Syntax
backingMode( STANDARD|RETAINED )
Parameters
Name | Description |
---|---|
mode | Either STANDARD or RETAINED |
Related
RETAINED
Description
Use this value in backingMode() to set the viewer to draw with a retained backing mode. This forces the viewer to copy the contents of the previous frame into the current frame each time draw() is called. This is useful for projects that need to paint onto the screen and preserve the screen's contents, for example, painting or drawing applications.
Syntax
backingMode( RETAINED )
Related
close()
Examples
function touched(touch)
--Exit if user taps
if touch.tapCount == 1 and touch.state == ENDED then
close()
end
end
Description
Closes the viewer and returns to the editor. Calling close() is functionally the same as pressing the on-screen Back button. This function is useful if you are using displayMode() with the FULLSCREEN_NO_BUTTONS mode
Syntax
close()
Related
Vector
Vector and Matrix Types
vec2
Examples
--Some vector operations
v1 = vec2( 1, 1 )
v2 = vec2( 4, 2 )
--Angle between
v1:angleBetween( v2 )
--Adding
v3 = v1 + v2
--Multiplying
v4 = v1 * 5.0
--Rotating by 45 degrees
v5 = v1:rotate(math.rad(45))
Description
This type represents a 2D vector. Most mathematical operators such as equality, addition, subtraction, multiplication and division are provided, so you can use vec2 data types similarly to how you use numerical types. In addition there are a number of methods, such as v:dot( vec2 ) that can be called on vec2 types, please see the related items below.
Syntax
vec2.x
vec2.y
myVec = vec2( 2.5, 10.0 )
-- Supports operators:
-- v = vec2 + vec2
-- v = vec2 - vec2
-- v = vec2 * scalar
-- v = vec2 / scalar
-- v = -vec2
-- b = vec2 == vec2
-- print( vec2 )
Parameters
Name | Description |
---|---|
x | float, the x component of this vec2 |
y | float, the y component of this vec2 |
Related
- vec2.dot
- vec2.normalize
- vec2.dist
- vec2.distSqr
- vec2.len
- vec2.lenSqr
- vec2.cross
- vec2.rotate
- vec2.rotate90
- vec2.angleBetween
vec2.dot( v )
Description
This method returns the scalar dot product between two vec2 types
Syntax
v1 = vec2( 1, 1 )
x = v1:dot( v )
Parameters
Name | Description |
---|---|
v | compute the dot product with this vec2 and v |
Returns
Dot product between this vec2 and v
Related
vec2.normalize()
Description
This method returns a normalized version of the vector
Syntax
v1 = vec2( 5, 5 )
v1 = v1:normalize()
Returns
Normalized version of this vec2
Related
vec2.dist( v )
Description
This method returns the distance between two vec2 types
Syntax
v1 = vec2( 1, 1 )
x = v1:dist( vec2(2, 2) )
Parameters
Name | Description |
---|---|
v | compute the distance between this vec2 and v |
Returns
Distance between this vec2 and v
Related
vec2.distSqr( v )
Description
This method returns the squared distance between two vec2 types
Syntax
v1 = vec2( 1, 1 )
x = v1:distSqr( vec2(2, 2) )
Parameters
Name | Description |
---|---|
v | compute the squared distance between this vec2 and v |
Returns
Squared distance between this vec2 and v
Related
vec2.len()
Description
This method returns the length of a vec2
Syntax
v1 = vec2( 2, 1 )
x = v1:len()
Returns
Length of this vec2
Related
vec2.lenSqr()
Description
This method returns the squared length of a vec2
Syntax
v1 = vec2( 2, 1 )
x = v1:lenSqr()
Returns
Squared length of this vec2
Related
vec2.cross( v )
Description
This method returns the cross product between two vec2 types
Syntax
v1 = vec2( 1, 1 )
v2 = v1:cross( vec2(2, 2) )
Parameters
Name | Description |
---|---|
v | compute the cross product of this vec2 and v |
Returns
Cross product of this vec2 and v
Related
vec2.rotate( angle )
Description
This method returns a rotated copy of a vec2 type. The angle is assumed to be radians.
Syntax
v1 = vec2( 1, 1 )
v1 = v1:rotate( math.rad(45) )
Parameters
Name | Description |
---|---|
angle | float, rotate this vector by angle in radians |
Returns
Rotated version of this vec2
Related
vec2.rotate90()
Description
This method returns a copy of a vec2 type, rotated 90 degrees.
Syntax
v1 = vec2( 1, 1 )
v1 = v1:rotate90()
Returns
Rotated version of this vec2
Related
vec2.angleBetween( v )
Description
This method returns the angle between this vec2 and v in radians.
Syntax
v1 = vec2( 1, 1 )
angle = math.deg( v1:angleBetween( vec2(5, 2) ) )
Parameters
Name | Description |
---|---|
v | compute the angle between this vec2 and v |
Returns
Angle between vec2 and v in radians
Related
vec3
Description
This type represents a 3D vector. Most mathematical operators such as equality, addition, subtraction, multiplication and division are provided, so you can use vec3 data as you would normally use numerical types. In addition there are a number of methods, such as v:dot( vec3 ) that can be called on vec3 types, please see the related items below.
Syntax
vec3.x
vec3.y
vec3.z
myVec = vec3( 1.0, 2.0, 3.0 )
v = vec3(1,2,3) + vec3(3,2,1)
v = vec3(1,1,1) * 5
Parameters
Name | Description |
---|---|
x | float, x dimension of this vector |
y | float, y dimension of this vector |
z | float, z dimension of this vector |
Related
vec3.dot( v )
Description
This method returns the scalar dot product between two vec3 types
Syntax
v1 = vec3( 1, 1, 1 )
x = v1:dot( v )
Parameters
Name | Description |
---|---|
v | compute the dot product with this vec3 and v |
Returns
Dot product between this vec3 and v
Related
vec3.normalize()
Description
This method returns a normalized version of the vector
Syntax
v1 = vec3( 5, 5, 5 )
v1 = v1:normalize()
Returns
Normalized version of this vec3
Related
vec3.dist( v )
Description
This method returns the distance between two vec3 types
Syntax
v1 = vec3( 1, 1, 1 )
x = v1:dist( vec3(2, 2, 2) )
Parameters
Name | Description |
---|---|
v | compute the distance between this vec3 and v |
Returns
Distance between this vec3 and v
Related
vec3.distSqr( v )
Description
This method returns the squared distance between two vec3 types
Syntax
v1 = vec3( 1, 1, 1 )
x = v1:distSqr( vec3(2, 2, 2) )
Parameters
Name | Description |
---|---|
v | compute the squared distance between this vec3 and v |
Returns
Squared distance between this vec3 and v
Related
vec3.len()
Description
This method returns the length of a vec3
Syntax
v1 = vec3( 2, 1, 0 )
x = v1:len()
Returns
Length of this vec3
Related
vec3.lenSqr()
Description
This method returns the squared length of a vec3
Syntax
v1 = vec3( 2, 1, 0 )
x = v1:lenSqr()
Returns
Squared length of this vec3
Related
vec3.cross( v )
Description
This method returns the cross product between two vec3 types
Syntax
v1 = vec3( 1, 1 )
v2 = v1:cross( vec3(2, 2) )
Parameters
Name | Description |
---|---|
v | compute the cross product of this vec3 and v |
Returns
Cross product of this vec3 and v
Related
matrix
Examples
matrix[x] = y
m1 = matrix( 1,2,3,…,16 )
m2 = matrix( 4,5,6,…,20)
-- Supports operators:
m = m1 + m2
m = m1 - m2
m = m1 * 10
m = m1 / 10
m = -m1
checkEqual = m1 == m2
print( m1 )
Description
This type represents a 4x4 column-major matrix. This matrix type is used to represent transformations in Codea, and can be used with functions such as modelMatrix() and viewMatrix(). The matrix type supports the following arithmetic operators: multiplication (between two matrices), multiplication by scalar, division by scalar, equality, and element-wise addition and subtraction.
Because this type is used to represent transformations it also provides a number of 3D transformation methods such as matrix:translate(x,y,z), matrix:rotate(angle,x,y,z). See the related items for a full list.
Constructing a matrix with no parameters returns the identity matrix. Passing 16 numbers when constructing a matrix will assign those values to the elements of the matrix. Individual matrix elements can be accessed by their index, for example m[1] for the first element and m[16] for the last element. Entries are defined such that the x,y,z translation components are stored in elements 13, 14, and 15 respectively.
Syntax
matrix[1] … matrix[16]
m = matrix()
m = matrix(1, 2, 3, …. 16)
m = matrix1 * matrix2
Parameters
Name | Description |
---|---|
element | float, an element of the matrix |
Returns
A new matrix with the given elements
Related
- modelMatrix
- matrix.rotate
- matrix.translate
- matrix.scale
- matrix.inverse
- matrix.transpose
- matrix.determinant
matrix.rotate( m, r, x, y, z )
Examples
m = matrix()
--Rotate about 0,0,1
rotated = m:rotate(30)
--Rotate by a given axis
rotated= m:rotate(30, 1, 0, 0)
Description
This method returns the matrix multiplied by a rotation matrix defining a rotation of angle degrees around the x,y,z axis or (0,0,1) if no axis is given.
Syntax
rotated = m:rotate( angle, axisX, axisY, axisZ )
Parameters
Name | Description |
---|---|
angle | float, the rotation in degrees |
axisX | float, the x component of the axis of rotation |
axisY | float, the y component of the axis of rotation |
axisZ | float, the z component of the axis of rotation |
Returns
A matrix which rotates m by the specified rotation
Related
matrix.translate( m, x, y, z )
Examples
m = matrix()
translated = m:translate(100,20,10)
Description
This method returns the matrix multiplied by a translation matrix defining a translation of x, y, z.
Syntax
translated = m:translate( x, y, z )
Parameters
Name | Description |
---|---|
x | float, the x component of translation |
y | float, the y component of translation |
z | float, optional, defaults to 0 – the z component of translation |
Returns
A matrix which translates m by the specified amount
Related
matrix.scale( m, x, y, z )
Examples
m = matrix()
s = m:scale(100,20,10)
--Uniform scaling
s = m:scale(5)
Description
This method returns the matrix scaled by a translation matrix defining a scaling to each axis.
Syntax
scaled = m:scale( x, y, z )
Parameters
Name | Description |
---|---|
x | float, the x component of scale, or the uniform scale if no other components are given |
y | float, optional, the y component of scale |
z | float, optional, defaults to 1 if x and y are both given, otherwise x – the z component of scale |
Returns
A matrix which scales m by the specified amount
Related
matrix.inverse( m )
Description
This method returns the inverse of the given matrix, if such an inverse exists. If no inverse exists, the result is a matrix of NaN values. The inverse of a matrix is a matrix such that m * mInv = I, where I is the identity matrix.
Syntax
inv = m:inverse()
Parameters
Name | Description |
---|---|
m | the matrix to invert |
Returns
A matrix which inverts m
Related
matrix.transpose( m )
Description
This method returns the transpose of the given matrix. The transpose of a matrix is a matrix that is flipped on the major diagonal (ie, elements 1,6,11,16). For example element 2 and element 5 are swapped, etc.
Syntax
transposed = m:transpose()
Parameters
Name | Description |
---|---|
m | the matrix to transpose |
Returns
A matrix which is the transpose of m
Related
matrix.determinant( m )
Description
This method returns the determinant of the given matrix. This has various uses for determining characteristics of a matrix, especially whether it is invertible or not.
Syntax
det = m:determinant()
Returns
A float equal to the determinant of m
Related
Accelerometer
Detecting Device Motion and Gravity
Gravity
Description
This global variable represents the current direction and amount of gravity relative to the screen orientation while the viewer is running. The y component of this vector will almost always be negative, indicating that the device is being held upright.
Syntax
Gravity
Gravity.x
Gravity.y
Gravity.z
Parameters
Name | Description |
---|---|
x | float, the amount of gravity in the x direction |
y | float, the amount of gravity in the y direction |
z | float, the amount of gravity in the z direction |
Related
UserAcceleration
Description
This global variable represents the current acceleration relative to the device while the viewer is running. You can use this to detect things such as shaking.
Syntax
UserAcceleration
UserAcceleration.x
UserAcceleration.y
UserAcceleration.z
Parameters
Name | Description |
---|---|
x | float, the amount of acceleration in the x direction |
y | float, the amount of acceleration in the y direction |
z | float, the amount of acceleration in the z direction |
Related
Network
Network Connections and Requests
openURL( url )
Examples
function touched(touch)
openURL( 'http://twolivesleft.com' )
end
Description
This function opens the URL specified by url in an external browser.
Syntax
openURL( url )
Parameters
Name | Description |
---|---|
url | string, the url to open |
HTTP Callback Overview
Description
HTTP requests are handled by the http.get function. This function accepts a url (string) as its first argument, and a success and failure function as its second and third arguments respectively. The more advanced form of http.get accepts a table of parameters as its fourth argument.
-- Success function format
function success( response string or image,
statusCode,
responseHeaders )
-- Failure function format
function fail( error )
Related
http.get( url, successFunction )
Examples
-- Downloading data
function setup()
textData = nil
-- Request some data
http.get( 'http:twolivesleft.com/hello.txt',
didGetData )
end
-- Our callback function
function didGetData( data, status, headers )
print( status..' : '..data )
end
-- Downloading an image
function setup()
logoImage = nil
-- Request some data
http.get( 'http:twolivesleft.com/logo.png',
didGetImage )
end
-- Our callback function
function didGetImage( theImage, status, head )
logoImage = theImage
end
function draw()
background(20,20,40)
if logoImage ~= nil then
sprite(logoImage, WIDTH/2,HEIGHT/2,WIDTH)
end
end
Description
This function allows you to send a http request to the url specified by url. The request is asynchronous, so you must provide a successFunction to be called when the request succeeds. The success or fail function will be called outside of your draw function at some point in the future. You may also provide additional parameters, such as a failure function, and request type by using the more advanced parameterTable form of the function. For details on the structure of the callback functions, please see the HTTP Callback Overview in the related items, below.
Note that the successFunction will be called if the request succeeds at all. This does not guarantee that the data was found. A 404 error will result in no data, but is an example of a successful request.
http.get has special behaviour when it comes to images in PNG, JPEG and other formats. Rather than provide the raw data in the successFunction callback, Codea will automatically convert the data to an image type, which you can then draw to the screen immediately.
Syntax
http.get( url, successFunction )
http.get( url, successFunction, failFunction )
http.get( url, success, fail, parameterTable )
Parameters
Name | Description |
---|---|
url | string, the url to submit the request |
successFunction | function, the function to be called when the request succeeds. This function will be called with an argument representing the returned data. |
failFunction | function, the function to be called when the request fails. This function will be called with a string argument containing the error. |
parameterTable | table, specifying advanced parameters |
"method" : "HEAD",\n "GET",\n "PUT",\n "POST",\n "DELETE"\n"headers" : table, string pairs\n for name and value\n of HTTP headers\n"data" : string, POST data.\n Only used for POST\n or PUT methods.\n"useragent" : string\n
Related
Storage
Storing Persistent Data
readImage( spriteKey )
Examples
-- Read a sprite into an image
myImage = readImage('Planet Cute:Heart')
Description
This function reads a stored sprite (i.e., a sprite that is visible in the sprite picker) into an image type. You can read from the included sprite packs, or your Documents and Dropbox sprite packs.
Syntax
readImage( spriteKey )
Parameters
Name | Description |
---|---|
spriteKey | string, name of sprite pack and sprite, separated by a colon (e.g., "Documents:MySprite") |
Returns
The image associated with spriteKey or nil if spriteKey doesn't exist or is invalid.
Related
saveImage( spriteKey, image )
Examples
-- Save a sprite into documents
function setup()
myImage = image(400,400)
setContext(myImage)
background(0,0,0,0)
fill(255,0,0)
ellipse(200,200,200)
setContext()
saveImage('Documents:Circle', myImage)
end
Description
This function saves an image into a sprite pack. Only user sprite packs (Documents and Dropbox) are permitted for this operation. If an existing sprite exists under the spriteKey name it will be overwritten, if nil is specified for the image parameter then the sprite at spriteKey will be deleted.
Note that if you are using a retina device, two files will be saved when using this function. A retina sized image with an "@2x" suffix, and a 50% scale non-retina image.
Note that if you save an image to your Dropbox sprite pack then you will have to open the sprite picker and sync your Dropbox sprite pack in order for the image to be uploaded to your Dropbox account.
Syntax
saveImage( spriteKey, image )
Parameters
Name | Description |
---|---|
spriteKey | string, name of sprite pack and sprite, separated by a colon (e.g., "Documents:MySprite") |
image | image, the image to be saved under spriteKey |
Related
readLocalData( key )
Examples
-- Load high score
-- Defaults to 0 if it doesn't exist
highscore = readLocalData('highscore', 0)
Description
This function reads a value associated with key from the local device storage for the current project.
Local storage for a particular project is unique to your device. That is, sharing your project will not share the associated data. This sort of storage is useful for things such as high scores, statistics, and any values you are likely to associate while a user is interacting with your game or simulation.
Syntax
readLocalData( key )
readLocalData( key, defaultValue )
Parameters
Name | Description |
---|---|
key | string, name of the piece of data you would like to get |
defaultValue | if the key doesn't exist, this value is returned instead |
Returns
The value associated with key, or defaultValue if key doesn't exist and defaultValue is specified. nil if key doesn't exist and defaultValue is not specified.
Related
saveLocalData( key, value )
Examples
-- Save high score
saveLocalData('highscore', currentScore)
Description
This function stores a value associated with key in the local device storage for the current project.
Local storage for a particular project is unique to your device. That is, sharing your project will not share the associated data. This sort of storage is useful for things such as high scores, statistics, and any values you are likely to associate while a user is interacting with your game or simulation.
Syntax
saveLocalData( key, value )
Parameters
Name | Description |
---|---|
key | string, name of the piece of data you would like to store |
value | the value to store under key |
Related
clearLocalData()
Description
This function clears all local data for the current project.
Local storage for a particular project is unique to your device. That is, sharing your project will not share the associated data. This sort of storage is useful for things such as high scores, statistics, and any values you are likely to associate while a user is interacting with your game or simulation.
Syntax
clearLocalData( )
Related
readProjectData( key )
Description
This function reads a value associated with key from the project storage for the current project.
Project storage is bundled with your project. That is, sharing your project will also share the associated data. This sort of storage is useful for things such procedurally generated levels, maps, and other static or dynamic data you may want to provide with your project.
Syntax
readProjectData( key )
readProjectData( key, defaultValue )
Parameters
Name | Description |
---|---|
key | string, name of the piece of data you would like to get |
defaultValue | if the key doesn't exist, this value is returned instead |
Returns
The value associated with key, or defaultValue if key doesn't exist and defaultValue is specified. nil if key doesn't exist and defaultValue is not specified.
Related
saveProjectData( key, value )
Description
This function stores a value associated with key in your project's storage.
Project storage is bundled with your project. That is, sharing your project will also share the associated data. This sort of storage is useful for things such procedurally generated levels, maps, and other static or dynamic data you may want to provide with your project.
Syntax
saveProjectData( key, value )
Parameters
Name | Description |
---|---|
key | string, name of the piece of data you would like to store |
value | the value to store under key |
Related
saveProjectInfo( key, value )
Description
This function allows you to save metadata about your project from within your code. For example, you may set the description that appears on the Project Browser page by calling saveProjectInfo() with 'description' as the key.
Syntax
saveProjectInfo( key, value )
Parameters
Name | Description |
---|---|
key | string, name of the project metadata to store. Currently supports "Description" and "Author" |
value | the value to store under key |
Related
readProjectInfo( key )
Description
This function reads a value associated with key from the project metadata for the current project.
Syntax
readProjectInfo( key )
Parameters
Name | Description |
---|---|
key | string, name of the piece of metadata you would like to get |
Returns
The value associated with key, or nil if the key does not exist
Related
clearProjectData()
Description
This function clears all project-stored data.
Project storage is bundled with your project. That is, sharing your project will also share the associated data. This sort of storage is useful for things such procedurally generated levels, maps, and other static or dynamic data you may want to provide with your project.
Syntax
clearProjectData( )
Related
readGlobalData( key )
Description
This function reads a value associated with key from the global storage on this device.
Global storage is shared among all projects on this device.
Syntax
readGlobalData( key )
readGlobalData( key, defaultValue )
Parameters
Name | Description |
---|---|
key | string, name of the piece of data you would like to get |
defaultValue | if the key doesn't exist, this value is returned instead |
Returns
The value associated with key, or defaultValue if key doesn't exist and defaultValue is specified. nil if key doesn't exist and defaultValue is not specified.
Related
saveGlobalData( key, value )
Description
This function stores a value associated with key in this device's global storage.
Global storage is shared among all projects on this device.
Syntax
saveGlobalData( key, value )
Parameters
Name | Description |
---|---|
key | string, name of the piece of data you would like to store |
value | the value to store under key |
Related
Updated