Codea icon Input & Motion

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

Guides

Input in Codea top ↑

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.

Three callbacks report pointer activity. hover(gesture) is called as the pointer moves over the viewer with no button held, scroll(gesture) is called for trackpad and scroll wheel scrolling, and pinch(gesture) is called for trackpad pinches. Each receives 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. For pinch, gesture.pinchDelta is the change in scale since the previous call.

local scrollY = 0
local hoverX, hoverY = 0, 0
local size = 40

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

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

function pinch(gesture)
    size = size * gesture.pinchDelta
end

function draw()
    background(40)
    fill(255)
    ellipse(hoverX, hoverY + scrollY, size, size)
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.

On-screen controls work like any other gamepad: find them in gamepad.all or read gamepad.current. Their isVirtual property is true. They appear when ready and use the same connected and disconnected callbacks as physical controllers. On-screen controls are disabled by default. Enable them by setting gamepad.virtual.style = gamepad.automatic.

Connecting a physical controller hides the on-screen controls and removes the on-screen controller from gamepad.all. Its held input is cleared. The requested style and control selection are preserved. After the last physical controller disconnects, on-screen controls return unless you have set the style to gamepad.none.

Configure on-screen controls through gamepad.virtual. This settings table is separate from the controllers you read input from.

Choose the presentation with gamepad.virtual.style:

- gamepad.automatic: Use native on-screen controls when available. If the platform doesn’t support them or cannot show them, use the built-in controls instead. - gamepad.builtin uses Carbide’s drawn controls. - gamepad.native uses only platform-native controls. - gamepad.none (default) disables on-screen controls without disabling physical controllers.

Choose buttons and sticks by assigning an array of gamepad.control constants to gamepad.virtual.controls. The default is the left stick and A button. Choose either the D-pad or the left stick; requesting both raises an error and leaves the existing selection unchanged. Native controls support additional buttons, sticks, a D-pad, shoulders and triggers. Built-in controls currently support only the left stick and A button; requesting other controls does not add them. Check a control’s available property when your game needs it. Carbide handles drawing and touch input for you.

For example:

function setup()
    gamepad.virtual.style = gamepad.automatic
    gamepad.virtual.controls = {gamepad.control.leftStick, gamepad.control.a}
    pos = vec2(WIDTH/2, HEIGHT/2)
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

Set gamepad.virtual.style = gamepad.none to hide controls for a menu. Set it back to the desired style to show them again. Your control selection is preserved. Settings take effect on the next input update. A controller being disabled clears its held input and leaves gamepad.all; keep reading gamepad.current to follow whichever controller the player uses.

Native controls may take a moment to appear. gamepad.virtual.status is starting while waiting and visible once ready. With explicit native style it reports unavailable on unsupported platforms and failed if the controls cannot be shown. disabled means the style is gamepad.none; suppressed means a physical controller is keeping the on-screen controls hidden. Automatic style handles selection and fallback for you.

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 ↑

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

Syntax

touch.id

An id that can be used to uniquely identify the touch

touch.state

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

Syntax

touch.began

true if the touch began with this event

touch.changed

Syntax

touch.changed

true if the touch moved with this event

touch.moving

Syntax

touch.moving

The same as changed

touch.ended

Syntax

touch.ended

true if the touch ended with this event

touch.cancelled

Syntax

touch.cancelled

true if the touch was cancelled

touch.tapCount

Syntax

touch.tapCount

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

touch.type

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

Syntax

touch.x

The x position of the touch (in screen coordinates)

touch.y

Syntax

touch.y

The y position of the touch (in screen coordinates)

touch.prevX

Syntax

touch.prevX

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

touch.prevY

Syntax

touch.prevY

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

touch.deltaX

Syntax

touch.deltaX

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

touch.deltaY

Syntax

touch.deltaY

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

touch.pos

Syntax

touch.pos

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

touch.prevPos

Syntax

touch.prevPos

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

touch.delta

Syntax

touch.delta

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

touch.force

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

Syntax

touch.maxForce

The maximum possible value of force

touch.timestamp

Syntax

touch.timestamp

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

touch.azimuth

Syntax

touch.azimuth

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

touch.altitude

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

Syntax

touch.radiusTolerance

The amount the estimated radius can vary due to hardware tolerances

touch.radius

Syntax

touch.radius

The estimated radius of the touch

touch.precisePos

Syntax

touch.precisePos

The precise location of the touch (if available)

touch.precisePrevPos

Syntax

touch.precisePrevPos

The previous precise location of the touch (if available)

touch.current

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)

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)

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

Syntax

touch.direct

touch.indirect

Syntax

touch.indirect

touch.pencil

Syntax

touch.pencil

touch.pointer

Syntax

touch.pointer

Constants - Touch State

BEGAN top ↑

Syntax

BEGAN

CHANGED top ↑

Syntax

CHANGED

MOVING top ↑

Syntax

MOVING

The same value as CHANGED

ENDED top ↑

Syntax

ENDED

CANCELLED top ↑

Syntax

CANCELLED

Gestures

gesture top ↑

Syntax

gesture

Represents a single gesture event. Passed to gesture recognizer callbacks and to the global hover(gesture), scroll(gesture) and pinch(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

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

Syntax

gesture.location

The location of the gesture event on the screen

gesture.translation

Syntax

gesture.translation

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

gesture.delta

Syntax

gesture.delta

The delta of the gesture event since last update

gesture.pinchScale

Syntax

gesture.pinchScale

The scale of a pinch gesture relative to its starting distance

gesture.pinchDelta

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

Syntax

gesture.pinchVelocity

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

gesture.rotationAngle

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

Syntax

gesture.rotationVelocity

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

gesture.touchCount

Syntax

gesture.touchCount

The current number of touches associated with this gesture

gesture.tap top ↑

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)

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

Syntax

gesture.tap.enabled

Enables/disables this gesture recognizer

gesture.tap.group

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 ↑

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)

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

Syntax

gesture.pan.enabled

Enables/disables this gesture recognizer

gesture.pan.group

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 ↑

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)

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

Syntax

gesture.pinch.enabled

Enables/disables this gesture recognizer

gesture.pinch.group

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 ↑

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)

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

Syntax

gesture.rotation.enabled

Enables/disables this gesture recognizer

gesture.rotation.group

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 ↑

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 ↑

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 ↑

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

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, scroll and pinch callbacks and pointer locking.

Keyboard

key.pressing(keyCode) top ↑

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 ↑

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 ↑

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 ↑

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 ↑

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 ↑

Syntax

press

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

press.keyCode

Syntax

press.keyCode

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

press.modifierFlags

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

Syntax

press.characters

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

Keyboard Modifier Masks top ↑

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 ↑

Syntax

key.alt

key.ctrl top ↑

Syntax

key.ctrl

key.cmd top ↑

Syntax

key.cmd

key.shift top ↑

Syntax

key.shift

Constants - Key Codes

key.leftAlt top ↑

Syntax

key.leftAlt

key.rightAlt top ↑

Syntax

key.rightAlt

key.leftCtrl top ↑

Syntax

key.leftCtrl

key.rightCtrl top ↑

Syntax

key.rightCtrl

key.leftCmd top ↑

Syntax

key.leftCmd

key.rightCmd top ↑

Syntax

key.rightCmd

key.leftShift top ↑

Syntax

key.leftShift

key.rightShift top ↑

Syntax

key.rightShift

key.esc top ↑

Syntax

key.esc

key.enter top ↑

Syntax

key.enter

The return key

key.tab top ↑

Syntax

key.tab

key.space top ↑

Syntax

key.space

key.backspace top ↑

Syntax

key.backspace

key.up top ↑

Syntax

key.up

key.down top ↑

Syntax

key.down

key.left top ↑

Syntax

key.left

key.right top ↑

Syntax

key.right

key.insert top ↑

Syntax

key.insert

key.delete top ↑

Syntax

key.delete

key.home top ↑

Syntax

key.home

key.end top ↑

Syntax

key.end

key.pageup top ↑

Syntax

key.pageup

key.pagedown top ↑

Syntax

key.pagedown

key.print top ↑

Syntax

key.print

key.plus top ↑

Syntax

key.plus

key.minus top ↑

Syntax

key.minus

key.leftbracket top ↑

Syntax

key.leftbracket

key.rightbracket top ↑

Syntax

key.rightbracket

key.semicolon top ↑

Syntax

key.semicolon

key.quote top ↑

Syntax

key.quote

key.comma top ↑

Syntax

key.comma

key.period top ↑

Syntax

key.period

key.slash top ↑

Syntax

key.slash

key.backslash top ↑

Syntax

key.backslash

key.nonUSBackslash top ↑

Syntax

key.nonUSBackslash

key.tilde top ↑

Syntax

key.tilde

key.f1 top ↑

Syntax

key.f1

key.f2 top ↑

Syntax

key.f2

key.f3 top ↑

Syntax

key.f3

key.f4 top ↑

Syntax

key.f4

key.f5 top ↑

Syntax

key.f5

key.f6 top ↑

Syntax

key.f6

key.f7 top ↑

Syntax

key.f7

key.f8 top ↑

Syntax

key.f8

key.f9 top ↑

Syntax

key.f9

key.f10 top ↑

Syntax

key.f10

key.f11 top ↑

Syntax

key.f11

key.f12 top ↑

Syntax

key.f12

key.numpad0 top ↑

Syntax

key.numpad0

key.numpad1 top ↑

Syntax

key.numpad1

key.numpad2 top ↑

Syntax

key.numpad2

key.numpad3 top ↑

Syntax

key.numpad3

key.numpad4 top ↑

Syntax

key.numpad4

key.numpad5 top ↑

Syntax

key.numpad5

key.numpad6 top ↑

Syntax

key.numpad6

key.numpad7 top ↑

Syntax

key.numpad7

key.numpad8 top ↑

Syntax

key.numpad8

key.numpad9 top ↑

Syntax

key.numpad9

key.num0 top ↑

Syntax

key.num0

key.num1 top ↑

Syntax

key.num1

key.num2 top ↑

Syntax

key.num2

key.num3 top ↑

Syntax

key.num3

key.num4 top ↑

Syntax

key.num4

key.num5 top ↑

Syntax

key.num5

key.num6 top ↑

Syntax

key.num6

key.num7 top ↑

Syntax

key.num7

key.num8 top ↑

Syntax

key.num8

key.num9 top ↑

Syntax

key.num9

key.a top ↑

Syntax

key.a

key.b top ↑

Syntax

key.b

key.c top ↑

Syntax

key.c

key.d top ↑

Syntax

key.d

key.e top ↑

Syntax

key.e

key.f top ↑

Syntax

key.f

key.g top ↑

Syntax

key.g

key.h top ↑

Syntax

key.h

key.i top ↑

Syntax

key.i

key.j top ↑

Syntax

key.j

key.k top ↑

Syntax

key.k

key.l top ↑

Syntax

key.l

key.m top ↑

Syntax

key.m

key.n top ↑

Syntax

key.n

key.o top ↑

Syntax

key.o

key.p top ↑

Syntax

key.p

key.q top ↑

Syntax

key.q

key.r top ↑

Syntax

key.r

key.s top ↑

Syntax

key.s

key.t top ↑

Syntax

key.t

key.u top ↑

Syntax

key.u

key.v top ↑

Syntax

key.v

key.w top ↑

Syntax

key.w

key.x top ↑

Syntax

key.x

key.y top ↑

Syntax

key.y

key.z top ↑

Syntax

key.z

Gamepad

gamepad top ↑

Syntax

gamepad

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

gamepad.all

Syntax

gamepad.all

A list of all currently connected gamepads

gamepad.current

Syntax

gamepad.current

The most recently used gamepad, falling back to the first connected controller until a controller is used. nil only when none is connected

gamepad.isVirtual

Syntax

gamepad.isVirtual

True for an on-screen controller. Physical gamepads return false.

gamepad.virtual

Syntax

gamepad.virtual

Settings for on-screen controls. This is a configuration table, not a controller. Read input through gamepad.current or gamepad.all.

gamepad.virtual.style

Syntax

gamepad.virtual.style

Choose gamepad.none (default), gamepad.automatic, gamepad.builtin or gamepad.native. Carbide handles drawing and touch input for you. This is the requested style; automatic fallback does not change its value. Assigning the same style again leaves the controls alone.

On-screen controls appear as one ordinary gamepad in gamepad.all when ready, and can become gamepad.current when used. They trigger the usual gamepad.connected and gamepad.disconnected callbacks. Physical and on-screen controllers report independent input. While any physical controller is connected, the on-screen controller is hidden and removed from gamepad.all. The requested style and controls are preserved and return after the last physical controller disconnects, unless the style is gamepad.none.

Configuration takes effect on the next input update. Changing style or controls clears held on-screen input. Set gamepad.none to remove the on-screen controller; retained references then report neutral input.

gamepad.virtual.style = gamepad.automatic
gamepad.virtual.controls = {gamepad.control.leftStick, gamepad.control.a}
-- In draw(), read gamepad.current or a controller from gamepad.all.
-- Set gamepad.virtual.style = gamepad.none to hide on-screen controls.

gamepad.virtual.controls

Syntax

gamepad.virtual.controls

Constants identifying the requested on-screen controls. Defaults to {gamepad.control.leftStick, gamepad.control.a}. Use the gamepad.control constants below. The array must be nonempty and contain unique constants. Strings are not accepted. Choose either gamepad.control.dpad or gamepad.control.leftStick; requesting both raises an error. Invalid assignments leave the existing configuration and held input unchanged.

Native controls use the platform’s layout. Built-in controls currently draw only the requested left stick and A button; other requested controls remain unavailable. Check properties such as pad.b.available before using a control. This selection does not restrict physical controllers.

The array is copied on assignment and reading returns a copy. Assign a new array to change the selection; editing gamepad.virtual.controls[1] alone has no effect. The selection is preserved while the style is gamepad.none.

gamepad.virtual.status

Syntax

gamepad.virtual.status

Read-only status, updated with input:

  • disabled: the style is gamepad.none (the initial status).
  • suppressed: on-screen controls are enabled but a physical controller is connected.
  • starting: waiting for native controls to become ready.
  • visible: built-in or native controls are ready and listed in gamepad.all.
  • unavailable: explicit native style is unsupported on this platform.
  • failed: explicit native style could not show the controls.

Automatic style uses built-in controls if native controls cannot be shown, so its status becomes visible. To retry explicit native style after a failure, set gamepad.none and then gamepad.native.

gamepad.none

Syntax

gamepad.none

Disable on-screen controls (the default). Physical controllers remain available.

gamepad.automatic

Syntax

gamepad.automatic

Use native on-screen controls when available. If the platform doesn’t support them or cannot show them, use the built-in controls instead.

gamepad.builtin

Syntax

gamepad.builtin

Use Carbide’s drawn controls. Currently supports only the left stick and A button.

gamepad.native

Syntax

gamepad.native

Use platform-native controls only (iOS/iPadOS 15 or newer, excluding Mac Catalyst). If the controls cannot be shown, gamepad.virtual.status reports unavailable or failed; this style does not fall back.

gamepad.connected

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

Syntax

gamepad.disconnected

Callback for when a gamepad is disconnected. It has already been removed from all and its held inputs cleared when this callback runs

gamepad.leftShoulder

Syntax

gamepad.leftShoulder

The left shoulder button

gamepad.rightShoulder

Syntax

gamepad.rightShoulder

The right shoulder button

gamepad.leftTrigger

Syntax

gamepad.leftTrigger

The left trigger

gamepad.rightTrigger

Syntax

gamepad.rightTrigger

The right trigger

gamepad.dpad

Syntax

gamepad.dpad

The directional pad

gamepad.leftStick

Syntax

gamepad.leftStick

gamepad.rightStick

Syntax

gamepad.rightStick

gamepad.leftStickButton

Syntax

gamepad.leftStickButton

gamepad.rightStickButton

Syntax

gamepad.rightStickButton

gamepad.a

Syntax

gamepad.a

gamepad.b

Syntax

gamepad.b

gamepad.x

Syntax

gamepad.x

gamepad.y

Syntax

gamepad.y

gamepad.home

Syntax

gamepad.home

gamepad.menu

Syntax

gamepad.menu

gamepad.options

Syntax

gamepad.options

gamepad.touchpadButton

Syntax

gamepad.touchpadButton

gamepad.touchpadSurface

Syntax

gamepad.touchpadSurface

gamepad.batteryLevel

Syntax

gamepad.batteryLevel

The battery charge, from 0 to 1

gamepad.batteryState

Syntax

gamepad.batteryState

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

gamepad.light

Syntax

gamepad.light

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

gamepad.playerIndex

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

Syntax

gamepad.vendorName

The name of the controller as reported by its maker

gamepad.unset

Syntax

gamepad.unset

gamepad.player1

Syntax

gamepad.player1

gamepad.player2

Syntax

gamepad.player2

gamepad.player3

Syntax

gamepad.player3

gamepad.player4

Syntax

gamepad.player4

gamepad.charging

Syntax

gamepad.charging

gamepad.discharging

Syntax

gamepad.discharging

gamepad.full

Syntax

gamepad.full

gamepad.unknown

Syntax

gamepad.unknown

gamepad.control

Syntax

gamepad.control

Constants for choosing the virtual gamepad’s on-screen controls. Use these in gamepad.virtual.controls; read input through properties such as pad.a and pad.leftStick. Selecting a control does not guarantee it is available in every style; check the control’s available property.

gamepad.control.a

Syntax

gamepad.control.a

A button.

gamepad.control.b

Syntax

gamepad.control.b

B button.

gamepad.control.x

Syntax

gamepad.control.x

X button.

gamepad.control.y

Syntax

gamepad.control.y

Y button.

gamepad.control.dpad

Syntax

gamepad.control.dpad

Directional pad.

gamepad.control.leftStick

Syntax

gamepad.control.leftStick

Left stick.

gamepad.control.rightStick

Syntax

gamepad.control.rightStick

Right stick.

gamepad.control.leftShoulder

Syntax

gamepad.control.leftShoulder

Left shoulder button.

gamepad.control.rightShoulder

Syntax

gamepad.control.rightShoulder

Right shoulder button.

gamepad.control.leftTrigger

Syntax

gamepad.control.leftTrigger

Left trigger.

gamepad.control.rightTrigger

Syntax

gamepad.control.rightTrigger

Right trigger.

gamepad.button

Syntax

gamepad.button

A button or trigger on a gamepad

gamepad.button.available

Syntax

gamepad.button.available

Whether this control exists on the physical controller (or is enabled on the virtual controller). Missing controls return neutral values.

gamepad.button.pressing

Syntax

gamepad.button.pressing

true while the button is held down

gamepad.button.pressed

Syntax

gamepad.button.pressed

true only in the frame the button went down

gamepad.button.released

Syntax

gamepad.button.released

true only in the frame the button came up

gamepad.button.value

Syntax

gamepad.button.value

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

gamepad.button.touching

Syntax

gamepad.button.touching

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

gamepad.directionalPad

Syntax

gamepad.directionalPad

A stick, directional pad or touchpad surface on a gamepad

gamepad.directionalPad.available

Syntax

gamepad.directionalPad.available

Whether this control exists on the physical controller (or is enabled on the virtual controller). Missing controls return zero axes.

gamepad.directionalPad.dir

Syntax

gamepad.directionalPad.dir

The direction, with each axis from -1 to 1

gamepad.directionalPad.x

Syntax

gamepad.directionalPad.x

gamepad.directionalPad.y

Syntax

gamepad.directionalPad.y

gamepad.directionalPad.left

Syntax

gamepad.directionalPad.left

gamepad.directionalPad.right

Syntax

gamepad.directionalPad.right

gamepad.directionalPad.up

Syntax

gamepad.directionalPad.up

gamepad.directionalPad.down

Syntax

gamepad.directionalPad.down

On-Screen Keyboard

keyboard.show() top ↑

Syntax

keyboard.show()

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

keyboard.hide() top ↑

Syntax

keyboard.hide()

Hides the on-screen keyboard

keyboard.visible top ↑

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 ↑

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.x

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

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

Syntax

mouse.pos

The current position of the pointer as a vec2

mouse.dx

Syntax

mouse.dx

The horizontal movement of the pointer since the last frame

mouse.dy

Syntax

mouse.dy

The vertical movement of the pointer since the last frame

mouse.delta

Syntax

mouse.delta

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

mouse.scroll

Syntax

mouse.scroll

The scroll wheel or trackpad scroll amount this frame

mouse.left

Syntax

mouse.left

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

mouse.middle

Syntax

mouse.middle

The middle mouse button

mouse.right

Syntax

mouse.right

The right mouse button

mouse.active

Syntax

mouse.active

Whether a mouse or trackpad is currently connected

mouse.visible

Syntax

mouse.visible

Gets or sets the visibility of the system pointer cursor

Motion

motion top ↑

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.available

Syntax

motion.available

Whether device-motion attitude reference frames are available on this host. Read-only; offer tilt controls only on supported devices. Wait for nonzero gravity before calibrating, because the first sample arrives asynchronously.

motion.autoStart

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)

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

Syntax

motion.referenceFrame

Reference frame constants for motion tracking.

motion.stop()

Syntax

motion.stop()

Stop tracking motion metrics and set autoStart to false.

motion.updateInterval

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

Syntax

motion.gravity

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

motion.acceleration

Syntax

motion.acceleration

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

motion.rotationRate

Syntax

motion.rotationRate

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

motion.sensorLocation

Syntax

motion.sensorLocation

Sensor location constants.

motion.heading

Syntax

motion.heading

The heading in degrees relative to the current reference frame.

Device Orientation

motion.attitude top ↑

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 ↑

Syntax

motion.magnetic

Magnetic field data.

motion.magneticAccuracy top ↑

Syntax

motion.magneticAccuracy

Magnetic field accuracy constants.