Codea icon Input & Motion

Reference › Touches, gestures, keyboard, mouse and device sensors

Guides

Input in Codea top ↑

Overview

Respond to touches and key presses with functions such as touched(touch) and keyPressed(press). You can also check what is happening in draw(): key.pressing(key.space) tells you whether Space is held, and mouse.x gives the pointer position.

Touch and keyboard events are delivered before draw() runs, so the state you read in draw() is up to date for that frame.

Touches

Define a global touched(touch) function to receive touches. It is called each time a touch changes: when a finger goes down, every time it moves, and when it lifts. On a Mac, or an iPad with a mouse or trackpad, a click arrives as a touch of type touch.pointer.

local touches = {}

function touched(touch)
    if touch.ended or touch.cancelled then
        touches[touch.id] = nil
    else
        touches[touch.id] = touch.pos
    end
end

function draw()
    background(40)
    fill(255, 100, 100)
    for id, pos in pairs(touches) do
        ellipse(pos.x, pos.y, 60, 60)
    end
end

Each touch provides:

  • touch.id, a number that stays the same for the life of the touch
  • touch.x, touch.y and touch.pos, the current position
  • touch.prevX, touch.prevY and touch.prevPos, the position at the previous event
  • touch.deltaX, touch.deltaY and touch.delta, the movement since the previous event
  • touch.began, touch.changed, touch.ended and touch.cancelled, which are true in the matching phase (touch.moving is the same as touch.changed)
  • touch.state, the phase as one of BEGAN, CHANGED, ENDED or CANCELLED (MOVING is the same value as CHANGED)
  • touch.tapCount, the number of quick taps in a row
  • touch.type, one of touch.direct, touch.indirect, touch.pencil or touch.pointer

Positions are in screen coordinates with the origin at the bottom left. Apple Pencil touches also report force, maxForce, azimuth, altitude, precisePos and precisePrevPos.

To poll instead of using the callback, read touch.current. It holds the first touch that is down, and keeps its last state after it ends.

function draw()
    background(40)
    local t = touch.current
    if t.began or t.changed then
        fill(255)
        ellipse(t.x, t.y, 80, 80)
    end
end

Touching Entities

Entities in scene.main receive touches through a touched method. Return true when the touch begins to keep receiving it until it ends. A touch kept by an entity is not passed to the global touched function.

function setup()
    scn = scene()
    scene.main = scn

    local e = scn:entity()
    function e:touched(touch)
        if touch.began then
            print("began", touch.x, touch.y)
        elseif touch.ended then
            print("ended")
        end
        return true
    end
end

Without hit testing, every entity with a touched method is offered every new touch. Set entity.hitTest = true to offer it only touches that land on its 2D or 3D physics body, as seen by the scene’s camera. For a 3D body the method also receives the raycast hit as a second argument.

Inside a callback, touch:makeExclusive(entity) gives a touch to that entity alone, and touch:cancel(scene) ends it for every entity in the scene that holds it.

Gestures

Gesture recognizers use the system’s tap, pan, pinch and rotation recognizers and call a function with a gesture when they fire. Keep a reference to each recognizer you create. It stops working once it is garbage collected.

function setup()
    zoom = 1
    offset = vec2(0, 0)

    pinch = gesture.pinch(function(g)
        zoom = zoom * g.pinchDelta
    end)

    pan = gesture.pan(function(g)
        offset = offset + g.delta
    end, 2, 2)

    doubleTap = gesture.tap(function(g)
        zoom = 1
        offset = vec2(0, 0)
    end, 2)
end

function draw()
    background(40)
    fill(100, 180, 255)
    local size = 120 * zoom
    rect(WIDTH/2 + offset.x - size/2, HEIGHT/2 + offset.y - size/2, size, size)
end

A two finger pan moves the square, a pinch scales it, and a double tap resets it. By default a touch is handled by one recognizer at a time. Give recognizers the same non-zero group to let them run together, for example pinch.group = 1 and pan.group = 1.

Keyboard

Hardware keyboards are supported on iPhone, iPad and Mac. The on-screen keyboard is described below.

Read key state from draw() with the key functions. key.pressing is true while a key is held. key.wasPressed and key.wasReleased are true only in the frame where the key went down or came up.

function setup()
    pos = vec2(WIDTH/2, HEIGHT/2)
end

function draw()
    background(40)
    local speed = 300 * time.delta
    if key.pressing(key.left) then pos.x = pos.x - speed end
    if key.pressing(key.right) then pos.x = pos.x + speed end
    if key.pressing(key.up) then pos.y = pos.y + speed end
    if key.pressing(key.down) then pos.y = pos.y - speed end
    if key.wasPressed(key.space) then print("jump") end

    fill(255)
    ellipse(pos.x, pos.y, 60, 60)
end

To react to each key as it happens, define keyPressed(press) and keyReleased(press). The key.press passed in holds the keyCode, the modifierFlags held at the time, and the characters the key typed. Use characters for shortcuts and individual key actions. For editable text, use keyboard.text as shown below: it handles Unicode, autocorrection, pasting, and composed characters without slicing UTF-8 strings yourself.

keyPressed and keyReleased are not called while a user interface text field has focus.

Modifier keys are reported as a bit field. key.modifiersPressed(key.cmd) is true while either Command key is held. Combine masks with | to require several at once:

function keyPressed(press)
    if press.keyCode == key.s and key.modifiersPressed(key.cmd | key.shift) then
        print("save as")
    end
end

On-Screen Keyboard

Call keyboard.show() to bring up the on-screen keyboard and keyboard.hide() to put it away. keyboard.visible is true while it is on screen. Touching the screen does not dismiss it.

What the player types collects in keyboard.text, including autocorrected and pasted text and the characters of languages such as Korean, which are composed as they are typed. Each insertion also calls keyPressed, so code written for a hardware keyboard keeps working.

function setup()
    keyboard.show()
end

function keyPressed(press)
    if press.keyCode == key.enter then
        print("You typed " .. keyboard.text)
        keyboard.text = ""
    end
end

function draw()
    background(40)
    fill(255)
    text(keyboard.text, WIDTH/2, HEIGHT - 100)
end

Mouse and Trackpad

On a Mac, or an iPad with a mouse or trackpad, the global mouse holds the pointer state. mouse.active is true while a mouse or trackpad is connected.

function draw()
    background(40)
    if mouse.left.pressed then
        fill(255, 200, 0)
    else
        fill(255)
    end
    ellipse(mouse.x, mouse.y, 40, 40)
end

mouse.x and mouse.y follow the pointer while it hovers and while a button is held. mouse.delta and mouse.scroll hold the movement and scrolling since the last frame. Set mouse.visible = false to hide the system pointer over the viewer.

Two callbacks report pointer activity. hover(gesture) is called as the pointer moves over the viewer with no button held, and scroll(gesture) is called for trackpad and scroll wheel scrolling. Both receive a gesture whose location is the pointer position. For scroll, gesture.delta is the scroll movement since the previous call, with positive y meaning up.

local scrollY = 0
local hoverX, hoverY = 0, 0

function scroll(gesture)
    scrollY = scrollY + gesture.delta.y
end

function hover(gesture)
    hoverX, hoverY = gesture.location.x, gesture.location.y
end

function draw()
    background(40)
    fill(255)
    ellipse(hoverX, hoverY + scrollY, 40, 40)
end

Gamepads

Game controllers connected to the device are listed in gamepad.all. gamepad.current is the controller used most recently, or nil if none is connected.

function setup()
    pos = vec2(WIDTH/2, HEIGHT/2)
    gamepad.connected = function(pad)
        print("connected", pad.vendorName)
    end
end

function draw()
    background(40)
    local pad = gamepad.current
    if pad then
        pos = pos + pad.leftStick.dir * 300 * time.delta
        if pad.a.pressed then print("A") end
    end
    fill(255)
    ellipse(pos.x, pos.y, 60, 60)
end

Controllers already connected when the project starts are in gamepad.all but do not trigger gamepad.connected.

Each button has pressing, which is true while it is held, pressed and released, which are true only in the frame it changed, and an analog value. Sticks, the directional pad and the touchpad surface report a dir vector along with x, y, left, right, up and down.

gamepad.virtual returns an on-screen gamepad with a stick at the bottom left and an A button at the bottom right, controlled by touch. While a controller is connected it is hidden and mirrors that controller, so a project can read the same buttons either way:

function setup()
    pad = gamepad.virtual
    pos = vec2(WIDTH/2, HEIGHT/2)
end

function draw()
    background(40)
    pos = pos + pad.leftStick.dir * 300 * time.delta
    if pad.a.pressed then print("A") end
    fill(255)
    ellipse(pos.x, pos.y, 60, 60)
end

Controlling a scene with parameters

Use Controls to rename, move, recolor, or hide the sphere, or make it squash and stretch. Try 1.5 + math.sin(time.elapsed) in the expression field to make its label move up and down.

The label uses style.textRenderer(style.atlas) because its font size is one world unit and the 3D camera magnifies it. Distance-field glyphs stay sharp as the label grows on screen. The native renderer rasterizes at the requested font size, so a one-point native label becomes blurry when enlarged. The camera uses camera.depthAndColor to clear both its color and depth buffers.

Controlling a scene with parameters

Download project Open in Codea to run this example.

Show code (64 lines)
-- Use this function to perform your initial setup
function setup()
    print("Hello Parameters!")

    -- Create a simple scene containing a model to play with
    scn = scene.default3d()
    rig = scn.camera:add(camera.rigs.orbit)
    scn.camera:get(camera).clearMode = camera.depthAndColor

    -- Basic entity with a sphere mesh
    ent = scn:entity()
    ent:add(mesh.sphere())

    mat = material.lit()
    mat.color = color.red
    ent.material = mat
    ent.expr = function() return 1.5 end

    -- Draw some text above the entity
    function ent:draw()
        -- Distance-field text stays sharp at this small world-space size.
        style.depth(true).textRenderer(style.atlas).fill(255).fontSize(1)
        shapeMode(CENTER)
        textAlign(CENTER | MIDDLE)
        matrix.translate(0, self.expr(), 0)
        text(self.name)
    end

    -- Auto-update/draw the scene
    scene.main = scn


    parameter.text("Name", ent.name, function(value)
        ent.name = value
    end)

    -- Expression idiom (use multiline as well)
    parameter.text("Expression", "1.5", function(value)
        ent.expr = load("return "..value) or function() return 0 end
    end, true)

    -- Y value for the entity
    parameter.number("Y", 0, 10, 0, function(value)
        ent.y = value
    end)

    -- (De)activate entity
    parameter.boolean("Active", true, function(value)
        print(value and "On" or "Off")
        ent.active = value
    end)

    -- Adjust entity material color
    parameter.color("Color", color.yellow, function(value)
        mat.color = value
    end)

    -- Do a simple tween to squash and stretch
    parameter.action("Action", function()
        scn:tween(ent):punch{sx=2, sy=0.5}:time(1)
    end)

end

Tracking more than one finger

Drag several fingers to move their circles independently. Each position is stored using touch.id and removed when the touch ends or is cancelled.

Tracking more than one finger

Download project Open in Codea to run this example.

-- Track simultaneous fingers by their stable touch IDs.
local fingers = {}
function setup() end
function draw()
    background(30, 35, 45)
    style.fill(255).fontSize(20).textAlign(CENTER | MIDDLE)
    text("Touch and drag to draw circles", WIDTH/2, HEIGHT - 40)
    for id, position in pairs(fingers) do
        style.fill(100, 220, 200).noStroke()
        ellipse(position.x, position.y, 70)
    end
end
function touched(t)
    if t.ended or t.cancelled then
        fingers[t.id] = nil
    else
        fingers[t.id] = vec2(t.x, t.y)
    end
end

Touches

touch top ↑

Type

Syntax

touch

Represents a single touch over time. Passed to the global touched(touch) function and to entity touched methods each time the touch begins, moves or ends

touch.id

Property

Syntax

touch.id

An id that can be used to uniquely identify the touch

touch.state

Property

Syntax

touch.state

The current state of the touch, can be:

  • BEGAN - the touch began
  • CHANGED - the touch moved (MOVING is the same value)
  • ENDED - the touch ended
  • CANCELLED - the touch was cancelled, usually by a gesture recognizer or the system

touch.began

Property

Syntax

touch.began

true if the touch began with this event

touch.changed

Property

Syntax

touch.changed

true if the touch moved with this event

touch.moving

Property

Syntax

touch.moving

The same as changed

touch.ended

Property

Syntax

touch.ended

true if the touch ended with this event

touch.cancelled

Property

Syntax

touch.cancelled

true if the touch was cancelled

touch.tapCount

Property

Syntax

touch.tapCount

The number of quick taps in a row at this location, starting at 1

touch.type

Property

Syntax

touch.type

The type of touch, can be:

  • touch.direct - a touch resulting from direct contact with the screen
  • touch.indirect - a touch that does not result from direct contact with the screen
  • touch.pencil - a touch from Apple Pencil
  • touch.pointer - a click from a mouse or trackpad

touch.x

Property

Syntax

touch.x

The x position of the touch (in screen coordinates)

touch.y

Property

Syntax

touch.y

The y position of the touch (in screen coordinates)

touch.prevX

Property

Syntax

touch.prevX

The previous x position of the touch (in screen coordinates)

touch.prevY

Property

Syntax

touch.prevY

The previous y position of the touch (in screen coordinates)

touch.deltaX

Property

Syntax

touch.deltaX

The change in x position since the previous event for this touch (in screen coordinates)

touch.deltaY

Property

Syntax

touch.deltaY

The change in y position since the previous event for this touch (in screen coordinates)

touch.pos

Property

Syntax

touch.pos

The position of the touch (in screen coordinates) as a vector

touch.prevPos

Property

Syntax

touch.prevPos

The previous position of the touch (in screen coordinates) as a vector

touch.delta

Property

Syntax

touch.delta

The change in position since the previous event for this touch (in screen coordinates) as a vector

touch.force

Property

Syntax

touch.force

The amount of force being applied, where 1 is an average touch. Reported for Apple Pencil and on devices with 3D Touch, otherwise 0

touch.maxForce

Property

Syntax

touch.maxForce

The maximum possible value of force

touch.timestamp

Property

Syntax

touch.timestamp

The time when this touch event occurred, in seconds since the device started

touch.azimuth

Property

Syntax

touch.azimuth

The direction the pencil points across the screen, in radians (only applies to pencil type touches)

touch.altitude

Property

Syntax

touch.altitude

The angle of the pencil above the screen, in radians. 0 is flat against the screen and math.pi / 2 is perpendicular to it (only applies to pencil type touches)

touch.radiusTolerance

Property

Syntax

touch.radiusTolerance

The amount the estimated radius can vary due to hardware tolerances

touch.radius

Property

Syntax

touch.radius

The estimated radius of the touch

touch.precisePos

Property

Syntax

touch.precisePos

The precise location of the touch (if available)

touch.precisePrevPos

Property

Syntax

touch.precisePrevPos

The previous precise location of the touch (if available)

touch.current

Property

Syntax

touch.current

The first touch that is currently down. It keeps its last state after the touch ends, until a new touch begins. Read it as touch.current

touch:cancel(scene)

Method

Syntax

touch:cancel(scene)

Cancels this touch for every entity in scene that holds it. Each of those entities receives the touch once more with the CANCELLED state

Parameters

scene scene.

The scene whose entities hold the touch

touch:makeExclusive(entity)

Method

Syntax

touch:makeExclusive(entity)

Gives this touch to entity alone. Other entities that hold the touch receive it with the CANCELLED state. Does nothing if another entity already holds it exclusively

Parameters

entity entity.

The entity that keeps the touch

touch.direct

Property

Syntax

touch.direct

touch.indirect

Property

Syntax

touch.indirect

touch.pencil

Property

Syntax

touch.pencil

touch.pointer

Property

Syntax

touch.pointer

Constants - Touch State

BEGAN top ↑

Property

Syntax

BEGAN

CHANGED top ↑

Property

Syntax

CHANGED

MOVING top ↑

Property

Syntax

MOVING

The same value as CHANGED

ENDED top ↑

Property

Syntax

ENDED

CANCELLED top ↑

Property

Syntax

CANCELLED

Gestures

gesture top ↑

Type

Syntax

gesture

Represents a single gesture event. Passed to gesture recognizer callbacks and to the global hover(gesture) and scroll(gesture) functions. Each kind of gesture fills in only the fields that apply to it:

  • tap - location
  • pan and scroll - location, translation, delta and touchCount
  • pinch - location, pinchScale, pinchDelta and pinchVelocity
  • rotation - location, rotationAngle and rotationVelocity
  • hover - location

gesture.state

Property

Syntax

gesture.state

The current state of the gesture, using the same constants as touches:

  • BEGAN - the gesture was recognized
  • CHANGED - the gesture moved or changed
  • ENDED - the gesture finished or was cancelled

A tap reports ENDED once it is recognized.

gesture.location

Property

Syntax

gesture.location

The location of the gesture event on the screen

gesture.translation

Property

Syntax

gesture.translation

The translation of the gesture event relative to its starting location, with positive y pointing up

gesture.delta

Property

Syntax

gesture.delta

The delta of the gesture event since last update

gesture.pinchScale

Property

Syntax

gesture.pinchScale

The scale of a pinch gesture relative to its starting distance

gesture.pinchDelta

Property

Syntax

gesture.pinchDelta

The ratio of the pinch scale to its value at the last update. Multiply a size by it to follow the pinch

gesture.pinchVelocity

Property

Syntax

gesture.pinchVelocity

The rate of change of the pinch scale, in scale factor per second

gesture.rotationAngle

Property

Syntax

gesture.rotationAngle

The change in angle of a rotation gesture since the last update, in degrees. Positive values are counter-clockwise, the same direction as rotate().

gesture.rotationVelocity

Property

Syntax

gesture.rotationVelocity

The rate of change of the rotation angle, in degrees per second

gesture.touchCount

Property

Syntax

gesture.touchCount

The current number of touches associated with this gesture

gesture.tap top ↑

Type

Syntax

gesture.tap

Tap gesture recognizer (using system gesture recognizer for implementation). The recognizer is removed when it is garbage collected, so keep a reference to it

gesture.tap(callback, tapCount, touchCount)

Constructor

Syntax

gesture.tap(callback, tapCount, touchCount)

Creates and registers a new tap gesture recognizer that will call callback(gesture) when recognized

Parameters

callback function.

The function to call with the gesture

tapCount integer, optional, default 1.

The number of taps required, such as 2 for a double tap

touchCount integer, optional, default 1.

The number of fingers required

Returns

gesture.tap

gesture.tap.enabled

Property

Syntax

gesture.tap.enabled

Enables/disables this gesture recognizer

gesture.tap.group

Property

Syntax

gesture.tap.group

Recognizers that share the same non-zero group can recognize at the same time. A recognizer in group 0 does not run alongside others

gesture.pan top ↑

Type

Syntax

gesture.pan

Pan gesture recognizer (using system gesture recognizer for implementation). The recognizer is removed when it is garbage collected, so keep a reference to it

gesture.pan(callback, minTouches, maxTouches, trackpad)

Constructor

Syntax

gesture.pan(callback, minTouches, maxTouches, trackpad)

Creates and registers a new pan gesture recognizer that will call callback(gesture) as the pan begins, moves and ends

Parameters

callback function.

The function to call with the gesture

minTouches integer, optional, default 1.

The fewest fingers that can perform the pan

maxTouches integer, optional, default 1.

The most fingers that can perform the pan

trackpad boolean, optional, default false.

Also recognize two finger trackpad scrolling as a pan

Returns

gesture.pan

gesture.pan.enabled

Property

Syntax

gesture.pan.enabled

Enables/disables this gesture recognizer

gesture.pan.group

Property

Syntax

gesture.pan.group

Recognizers that share the same non-zero group can recognize at the same time. A recognizer in group 0 does not run alongside others

gesture.pinch top ↑

Type

Syntax

gesture.pinch

Pinch gesture recognizer (using system gesture recognizer for implementation). The recognizer is removed when it is garbage collected, so keep a reference to it

gesture.pinch(callback)

Constructor

Syntax

gesture.pinch(callback)

Creates and registers a new pinch gesture recognizer that will call callback(gesture) when recognized

Parameters

callback function.

Function called with the gesture object when its state changes.

Returns

gesture.pinch

gesture.pinch.enabled

Property

Syntax

gesture.pinch.enabled

Enables/disables this gesture recognizer

gesture.pinch.group

Property

Syntax

gesture.pinch.group

Recognizers that share the same non-zero group can recognize at the same time. A recognizer in group 0 does not run alongside others

gesture.rotation top ↑

Type

Syntax

gesture.rotation

Rotation gesture recognizer (using system gesture recognizer for implementation). The recognizer is removed when it is garbage collected, so keep a reference to it

gesture.rotation(callback)

Constructor

Syntax

gesture.rotation(callback)

Creates and registers a new rotation gesture recognizer that will call callback(gesture) when recognized

Parameters

callback function.

Function called with the gesture object when its state changes.

Returns

gesture.rotation

gesture.rotation.enabled

Property

Syntax

gesture.rotation.enabled

Enables/disables this gesture recognizer

gesture.rotation.group

Property

Syntax

gesture.rotation.group

Recognizers that share the same non-zero group can recognize at the same time. A recognizer in group 0 does not run alongside others

Input

Keyboard top ↑

Overview

Functions and constants for reading a hardware keyboard. Key events also call the global keyPressed(press) and keyReleased(press) functions, except while a user interface text field has focus

Use key.pressing for continuous movement and key.wasPressed for a one-off action. Multiply movement speed by time.delta so it does not depend on the frame rate. Modifier masks such as key.cmd and key.shift can be combined with |. For entered text, use keyboard.text so composition, autocorrection, and Unicode editing are handled by the system.

function setup()
    x = WIDTH / 2
end

function draw()
    background(30)
    if key.pressing(key.left) then x = x - 200 * time.delta end
    if key.pressing(key.right) then x = x + 200 * time.delta end
    if key.wasPressed(key.space) then x = WIDTH / 2 end
    fill(255)
    ellipse(x, HEIGHT / 2, 40)
end

See Input for key callbacks and shortcut examples.

On-Screen Keyboard top ↑

Overview

The on-screen keyboard. While it is shown, typing sets keyboard.text and also calls the global keyPressed(press) and keyReleased(press) functions, one after the other, for each insertion. press.characters holds the inserted text and press.keyCode is set for letters, digits, space, return and backspace. A hardware keyboard types into the same text while the on-screen keyboard is shown.

Use the buffer as the source of truth for text entry; do not append press.characters to it yourself, which would duplicate insertions. Clear or prefill the buffer before showing the keyboard. With a hardware keyboard attached, text entry can work even when keyboard.visible is false.

function setup()
    keyboard.text = ""
    keyboard.show()
end

function keyPressed(press)
    if press.keyCode == key.enter then
        print("Entered:", keyboard.text)
        keyboard.hide()
    end
end

function draw()
    background(30)
    fill(255)
    shapeMode(CENTER)
    text(keyboard.text, WIDTH / 2, HEIGHT / 2)
end

Mouse top ↑

Overview

The pointer state on a Mac, or an iPad with a mouse or trackpad. The global hover(gesture) and scroll(gesture) functions are also called for pointer movement and scrolling

Positions use drawing coordinates: the origin is at the lower-left of the viewer. mouse.delta and mouse.scroll are changes for the current frame, not accumulated positions. mouse.left.pressed stays true while dragging; compare it with its previous value to detect a new click. Check mouse.active before showing pointer-only UI, and keep a touch alternative for devices without a mouse.

function setup()
    position = vec2(WIDTH / 2, HEIGHT / 2)
end

function draw()
    background(30)
    if mouse.active and mouse.left.pressed then
        position = mouse.pos
    end
    fill(255, 190, 70)
    ellipse(position.x, position.y, 60)
end

See Input for hover and scroll callbacks and pointer locking.

Keyboard

key.pressing(keyCode) top ↑

Function

Syntax

key.pressing(keyCode)

Queries whether the key is currently held down

Parameters

keyCode constant.

The keyCode to query

Returns

boolean

Is the key held down

key.wasPressed(keyCode) top ↑

Function

Syntax

key.wasPressed(keyCode)

Queries whether the key went down since the previous frame

Parameters

keyCode constant.

The keyCode to query

Returns

boolean

Was the key pressed down this frame

key.wasReleased(keyCode) top ↑

Function

Syntax

key.wasReleased(keyCode)

Queries whether the key came up since the previous frame

Parameters

keyCode constant.

The keyCode to query

Returns

boolean

Was the key released this frame

key.modifiers() top ↑

Function

Syntax

key.modifiers()

Queries the current key modifiers as a bit field, which is composed of the following bit mask constants:

  • key.alt
  • key.ctrl
  • key.cmd
  • key.shift

Use key.pressing(keyCode) to query individual keys such as key.leftAlt.

Returns

integer

The modifiers currently held

key.modifiersPressed(modifiers) top ↑

Function

Syntax

key.modifiersPressed(modifiers)

Queries whether all of the supplied key modifiers are currently held. Combine masks with |, as in key.modifiersPressed(key.cmd | key.shift)

Parameters

modifiers constant.

The key modifiers to query as a bit field

Returns

boolean

Are the key modifiers currently pressed

press top ↑

Type

Syntax

press

A single key event, passed to the global keyPressed(press) and keyReleased(press) functions

press.keyCode

Property

Syntax

press.keyCode

The key, as one of the key key code constants such as key.a or key.space

press.modifierFlags

Property

Syntax

press.modifierFlags

The modifiers held during this key event, as a bit field of key.alt, key.ctrl, key.cmd and key.shift

press.characters

Property

Syntax

press.characters

The text produced by the key, taking modifiers such as shift into account

Keyboard Modifier Masks top ↑

Overview

These are bit masks for key.modifiers(), key.modifiersPressed() and press.modifierFlags. Each one covers both the left and right key. They are not key codes, so use key.leftAlt and similar with key.pressing()

Keyboard Modifier Masks

key.alt top ↑

Property

Syntax

key.alt

key.ctrl top ↑

Property

Syntax

key.ctrl

key.cmd top ↑

Property

Syntax

key.cmd

key.shift top ↑

Property

Syntax

key.shift

Constants - Key Codes

key.leftAlt top ↑

Property

Syntax

key.leftAlt

key.rightAlt top ↑

Property

Syntax

key.rightAlt

key.leftCtrl top ↑

Property

Syntax

key.leftCtrl

key.rightCtrl top ↑

Property

Syntax

key.rightCtrl

key.leftCmd top ↑

Property

Syntax

key.leftCmd

key.rightCmd top ↑

Property

Syntax

key.rightCmd

key.leftShift top ↑

Property

Syntax

key.leftShift

key.rightShift top ↑

Property

Syntax

key.rightShift

key.esc top ↑

Property

Syntax

key.esc

key.enter top ↑

Property

Syntax

key.enter

The return key

key.tab top ↑

Property

Syntax

key.tab

key.space top ↑

Property

Syntax

key.space

key.backspace top ↑

Property

Syntax

key.backspace

key.up top ↑

Property

Syntax

key.up

key.down top ↑

Property

Syntax

key.down

key.left top ↑

Property

Syntax

key.left

key.right top ↑

Property

Syntax

key.right

key.insert top ↑

Property

Syntax

key.insert

key.delete top ↑

Property

Syntax

key.delete

key.home top ↑

Property

Syntax

key.home

key.end top ↑

Property

Syntax

key.end

key.pageup top ↑

Property

Syntax

key.pageup

key.pagedown top ↑

Property

Syntax

key.pagedown

key.print top ↑

Property

Syntax

key.print

key.plus top ↑

Property

Syntax

key.plus

key.minus top ↑

Property

Syntax

key.minus

key.leftbracket top ↑

Property

Syntax

key.leftbracket

key.rightbracket top ↑

Property

Syntax

key.rightbracket

key.semicolon top ↑

Property

Syntax

key.semicolon

key.quote top ↑

Property

Syntax

key.quote

key.comma top ↑

Property

Syntax

key.comma

key.period top ↑

Property

Syntax

key.period

key.slash top ↑

Property

Syntax

key.slash

key.backslash top ↑

Property

Syntax

key.backslash

key.nonUSBackslash top ↑

Property

Syntax

key.nonUSBackslash

key.tilde top ↑

Property

Syntax

key.tilde

key.f1 top ↑

Property

Syntax

key.f1

key.f2 top ↑

Property

Syntax

key.f2

key.f3 top ↑

Property

Syntax

key.f3

key.f4 top ↑

Property

Syntax

key.f4

key.f5 top ↑

Property

Syntax

key.f5

key.f6 top ↑

Property

Syntax

key.f6

key.f7 top ↑

Property

Syntax

key.f7

key.f8 top ↑

Property

Syntax

key.f8

key.f9 top ↑

Property

Syntax

key.f9

key.f10 top ↑

Property

Syntax

key.f10

key.f11 top ↑

Property

Syntax

key.f11

key.f12 top ↑

Property

Syntax

key.f12

key.numpad0 top ↑

Property

Syntax

key.numpad0

key.numpad1 top ↑

Property

Syntax

key.numpad1

key.numpad2 top ↑

Property

Syntax

key.numpad2

key.numpad3 top ↑

Property

Syntax

key.numpad3

key.numpad4 top ↑

Property

Syntax

key.numpad4

key.numpad5 top ↑

Property

Syntax

key.numpad5

key.numpad6 top ↑

Property

Syntax

key.numpad6

key.numpad7 top ↑

Property

Syntax

key.numpad7

key.numpad8 top ↑

Property

Syntax

key.numpad8

key.numpad9 top ↑

Property

Syntax

key.numpad9

key.num0 top ↑

Property

Syntax

key.num0

key.num1 top ↑

Property

Syntax

key.num1

key.num2 top ↑

Property

Syntax

key.num2

key.num3 top ↑

Property

Syntax

key.num3

key.num4 top ↑

Property

Syntax

key.num4

key.num5 top ↑

Property

Syntax

key.num5

key.num6 top ↑

Property

Syntax

key.num6

key.num7 top ↑

Property

Syntax

key.num7

key.num8 top ↑

Property

Syntax

key.num8

key.num9 top ↑

Property

Syntax

key.num9

key.a top ↑

Property

Syntax

key.a

key.b top ↑

Property

Syntax

key.b

key.c top ↑

Property

Syntax

key.c

key.d top ↑

Property

Syntax

key.d

key.e top ↑

Property

Syntax

key.e

key.f top ↑

Property

Syntax

key.f

key.g top ↑

Property

Syntax

key.g

key.h top ↑

Property

Syntax

key.h

key.i top ↑

Property

Syntax

key.i

key.j top ↑

Property

Syntax

key.j

key.k top ↑

Property

Syntax

key.k

key.l top ↑

Property

Syntax

key.l

key.m top ↑

Property

Syntax

key.m

key.n top ↑

Property

Syntax

key.n

key.o top ↑

Property

Syntax

key.o

key.p top ↑

Property

Syntax

key.p

key.q top ↑

Property

Syntax

key.q

key.r top ↑

Property

Syntax

key.r

key.s top ↑

Property

Syntax

key.s

key.t top ↑

Property

Syntax

key.t

key.u top ↑

Property

Syntax

key.u

key.v top ↑

Property

Syntax

key.v

key.w top ↑

Property

Syntax

key.w

key.x top ↑

Property

Syntax

key.x

key.y top ↑

Property

Syntax

key.y

key.z top ↑

Property

Syntax

key.z

Gamepad

gamepad top ↑

Type

Syntax

gamepad

A game controller. Read gamepad.all, gamepad.current and gamepad.virtual to get one

gamepad.all

Property

Syntax

gamepad.all

A list of all currently connected gamepads

gamepad.current

Property

Syntax

gamepad.current

The most recently used gamepad, or nil if none is connected

gamepad.virtual

Property

Syntax

gamepad.virtual

Gets the on-screen gamepad, creating it on first use. It shows a stick at the bottom left and an A button at the bottom right, controlled by touch. While a controller is connected it is hidden and mirrors gamepad.current

gamepad.connected

Property

Syntax

gamepad.connected

Callback for when a gamepad is connected. Gamepads that are already connected when the project starts are listed in gamepad.all and do not trigger it

gamepad.disconnected

Property

Syntax

gamepad.disconnected

Callback for when a gamepad is disconnected

gamepad.leftShoulder

Property

Syntax

gamepad.leftShoulder

The left shoulder button

gamepad.rightShoulder

Property

Syntax

gamepad.rightShoulder

The right shoulder button

gamepad.leftTrigger

Property

Syntax

gamepad.leftTrigger

The left trigger

gamepad.rightTrigger

Property

Syntax

gamepad.rightTrigger

The right trigger

gamepad.dpad

Property

Syntax

gamepad.dpad

The directional pad

gamepad.leftStick

Property

Syntax

gamepad.leftStick

gamepad.rightStick

Property

Syntax

gamepad.rightStick

gamepad.leftStickButton

Property

Syntax

gamepad.leftStickButton

gamepad.rightStickButton

Property

Syntax

gamepad.rightStickButton

gamepad.a

Property

Syntax

gamepad.a

gamepad.b

Property

Syntax

gamepad.b

gamepad.x

Property

Syntax

gamepad.x

gamepad.y

Property

Syntax

gamepad.y

gamepad.home

Property

Syntax

gamepad.home

gamepad.menu

Property

Syntax

gamepad.menu

gamepad.options

Property

Syntax

gamepad.options

gamepad.touchpadButton

Property

Syntax

gamepad.touchpadButton

gamepad.touchpadSurface

Property

Syntax

gamepad.touchpadSurface

gamepad.batteryLevel

Property

Syntax

gamepad.batteryLevel

The battery charge, from 0 to 1

gamepad.batteryState

Property

Syntax

gamepad.batteryState

The battery state, one of gamepad.charging, gamepad.discharging, gamepad.full or gamepad.unknown

gamepad.light

Property

Syntax

gamepad.light

The color of the controller’s light, on controllers that have one

gamepad.playerIndex

Property

Syntax

gamepad.playerIndex

The player number shown on the controller, one of gamepad.unset, gamepad.player1, gamepad.player2, gamepad.player3 or gamepad.player4

gamepad.vendorName

Property

Syntax

gamepad.vendorName

The name of the controller as reported by its maker

gamepad.unset

Property

Syntax

gamepad.unset

gamepad.player1

Property

Syntax

gamepad.player1

gamepad.player2

Property

Syntax

gamepad.player2

gamepad.player3

Property

Syntax

gamepad.player3

gamepad.player4

Property

Syntax

gamepad.player4

gamepad.charging

Property

Syntax

gamepad.charging

gamepad.discharging

Property

Syntax

gamepad.discharging

gamepad.full

Property

Syntax

gamepad.full

gamepad.unknown

Property

Syntax

gamepad.unknown

gamepad.button

Type

Syntax

gamepad.button

A button or trigger on a gamepad

gamepad.button.pressing

Property

Syntax

gamepad.button.pressing

true while the button is held down

gamepad.button.pressed

Property

Syntax

gamepad.button.pressed

true only in the frame the button went down

gamepad.button.released

Property

Syntax

gamepad.button.released

true only in the frame the button came up

gamepad.button.value

Property

Syntax

gamepad.button.value

How far the button is pressed, from 0 to 1. Triggers report values in between

gamepad.button.touching

Property

Syntax

gamepad.button.touching

true while a finger rests on the button, on controllers that can sense it

gamepad.directionalPad

Type

Syntax

gamepad.directionalPad

A stick, directional pad or touchpad surface on a gamepad

gamepad.directionalPad.dir

Property

Syntax

gamepad.directionalPad.dir

The direction, with each axis from -1 to 1

gamepad.directionalPad.x

Property

Syntax

gamepad.directionalPad.x

gamepad.directionalPad.y

Property

Syntax

gamepad.directionalPad.y

gamepad.directionalPad.left

Property

Syntax

gamepad.directionalPad.left

gamepad.directionalPad.right

Property

Syntax

gamepad.directionalPad.right

gamepad.directionalPad.up

Property

Syntax

gamepad.directionalPad.up

gamepad.directionalPad.down

Property

Syntax

gamepad.directionalPad.down

On-Screen Keyboard

keyboard.show() top ↑

Function

Syntax

keyboard.show()

Shows the on-screen keyboard. It stays up when the screen is touched, until keyboard.hide() is called

keyboard.hide() top ↑

Function

Syntax

keyboard.hide()

Hides the on-screen keyboard

keyboard.visible top ↑

Property

Syntax

keyboard.visible

true while the on-screen keyboard is on screen. With a hardware keyboard attached, the system may not show it after keyboard.show()

keyboard.text top ↑

Property

Syntax

keyboard.text

The text typed so far, including text from autocorrection, pasting, and characters still being composed in languages such as Korean or Japanese. Set it to replace the text, for example keyboard.text = "" to clear it

Mouse

mouse top ↑

Module

mouse.x

Property

Syntax

mouse.x

The current horizontal position of the pointer in screen coordinates. Updated while the pointer hovers over the viewer and while a button is held

mouse.y

Property

Syntax

mouse.y

The current vertical position of the pointer in screen coordinates. Updated while the pointer hovers over the viewer and while a button is held

mouse.pos

Property

Syntax

mouse.pos

The current position of the pointer as a vec2

mouse.dx

Property

Syntax

mouse.dx

The horizontal movement of the pointer since the last frame

mouse.dy

Property

Syntax

mouse.dy

The vertical movement of the pointer since the last frame

mouse.delta

Property

Syntax

mouse.delta

The movement of the pointer since the last frame as a vec2

mouse.scroll

Property

Syntax

mouse.scroll

The scroll wheel or trackpad scroll amount this frame

mouse.left

Property

Syntax

mouse.left

The left mouse button. Trackpad clicks also count as the left button

mouse.middle

Property

Syntax

mouse.middle

The middle mouse button

mouse.right

Property

Syntax

mouse.right

The right mouse button

mouse.active

Property

Syntax

mouse.active

Whether a mouse or trackpad is currently connected

mouse.visible

Property

Syntax

mouse.visible

Gets or sets the visibility of the system pointer cursor

Motion

motion top ↑

Module

Read the device’s acceleration, rotation, and orientation to respond to tilts and movement. Motion tracking uses battery power; call motion.stop() when you no longer need it.

motion.autoStart

Property

Syntax

motion.autoStart

If set, motion tracking will start automatically as soon as any attribute is read. Default is true.

Set to false if you want to control when motion is tracked manually using the start and stop functions.

motion.start(referenceFrame)

Function

Syntax

motion.start(referenceFrame)

Start tracking motion metrics.

  • motion.referenceFrame.XArbitraryZVertical (default): The X-axis is arbitrary and the Z-axis is vertical.
  • motion.referenceFrame.XArbitraryCorrectedZVertical: The X-axis is arbitrary and the Z-axis is vertical. If available, the magnetometer will be used to correct for accumulated yaw errors.
  • motion.referenceFrame.XMagneticNorthZVertical: The X-axis points toward the magnetic north and the Z-axis is vertical.
  • motion.referenceFrame.XTrueNorthZVertical: The X-axis points toward the true north and the Z-axis is vertical.

Parameters

referenceFrame number.

The reference frame in which to track motion metrics. Can be one of the following values:

motion.referenceFrame

Property

Syntax

motion.referenceFrame

Reference frame constants for motion tracking.

motion.stop()

Function

Syntax

motion.stop()

Stop tracking motion metrics and set autoStart to false.

motion.updateInterval

Property

Syntax

motion.updateInterval

The interval, in seconds, at which motion data is updated. This value can be set to control the frequency of motion updates. A lower value means more frequent updates, which can provide smoother motion tracking but may consume more power. The default value is 1/30 second.

Note that the interval is clamped between limits defined by the system.

motion.gravity

Property

Syntax

motion.gravity

The gravity vector in the device’s reference frame. This vector is automatically rotated to follow device orientation changes.

motion.acceleration

Property

Syntax

motion.acceleration

The acceleration vector in the device’s reference frame. This vector is automatically rotated to follow device orientation changes.

motion.rotationRate

Property

Syntax

motion.rotationRate

The rotation rate in the device’s reference frame. This vector is automatically rotated to follow device orientation changes.

motion.sensorLocation

Property

Syntax

motion.sensorLocation

Sensor location constants.

motion.heading

Property

Syntax

motion.heading

The heading in degrees relative to the current reference frame.

Device Orientation

motion.attitude top ↑

Property

Syntax

motion.attitude

Represents a measurement of your device attitude. This orientation of a body relative to a given frame of reference.

You can set motion.attitude.referenceFrame to specify the frame of reference in which the attitude is expressed.

The value can be one of the following motion.referenceFrame.XArbitraryZVertical, motion.referenceFrame.XArbitraryCorrectedZVertical, motion.referenceFrame.XMagneticNorthZVertical, motion.referenceFrame.XTrueNorthZVertical.

Magnetic Field Data

motion.magnetic top ↑

Property

Syntax

motion.magnetic

Magnetic field data.

motion.magneticAccuracy top ↑

Property

Syntax

motion.magneticAccuracy

Magnetic field accuracy constants.