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.
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
endEach touch provides:
touch.id, a number that stays the same for the life of the touchtouch.x, touch.y and touch.pos, the current positiontouch.prevX, touch.prevY and touch.prevPos, the position at the previous eventtouch.deltaX, touch.deltaY and touch.delta, the movement since the previous eventtouch.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 rowtouch.type, one of touch.direct, touch.indirect, touch.pencil or touch.pointerPositions 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
endEntities 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
endWithout 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.
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)
endA 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.
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)
endTo 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
endCall 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)
endOn 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)
endmouse.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)
endGame 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)
endControllers 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)
endSet 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.
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.
Download project Open in Codea to run this example.
-- 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
Drag several fingers to move their circles independently. Each position is stored using touch.id and removed when the touch ends or is cancelled.
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
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
An id that can be used to uniquely identify the touch
touch.state
The current state of the touch, can be:
BEGAN - the touch beganCHANGED - the touch moved (MOVING is the same value)ENDED - the touch endedCANCELLED - the touch was cancelled, usually by a gesture recognizer or the systemtouch.began
true if the touch began with this event
touch.changed
true if the touch moved with this event
touch.moving
The same as changed
touch.ended
true if the touch ended with this event
touch.cancelled
true if the touch was cancelled
touch.tapCount
The number of quick taps in a row at this location, starting at 1
touch.type
The type of touch, can be:
touch.direct - a touch resulting from direct contact with the screentouch.indirect - a touch that does not result from direct contact with the screentouch.pencil - a touch from Apple Penciltouch.pointer - a click from a mouse or trackpadtouch.x
The x position of the touch (in screen coordinates)
touch.y
The y position of the touch (in screen coordinates)
touch.prevX
The previous x position of the touch (in screen coordinates)
touch.prevY
The previous y position of the touch (in screen coordinates)
touch.deltaX
The change in x position since the previous event for this touch (in screen coordinates)
touch.deltaY
The change in y position since the previous event for this touch (in screen coordinates)
touch.pos
The position of the touch (in screen coordinates) as a vector
touch.prevPos
The previous position of the touch (in screen coordinates) as a vector
touch.delta
The change in position since the previous event for this touch (in screen coordinates) as a vector
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
The maximum possible value of force
touch.timestamp
The time when this touch event occurred, in seconds since the device started
touch.azimuth
The direction the pencil points across the screen, in radians (only applies to pencil type touches)
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
The amount the estimated radius can vary due to hardware tolerances
touch.radius
The estimated radius of the touch
touch.precisePos
The precise location of the touch (if available)
touch.precisePrevPos
The previous precise location of the touch (if available)
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)
Cancels this touch for every entity in scene that holds it. Each of those entities receives the touch once more with the CANCELLED state
| scene | scene. The scene whose entities hold the touch |
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
| entity | entity. The entity that keeps the touch |
touch.direct
touch.indirect
touch.pencil
touch.pointer
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:
locationlocation, translation, delta and touchCountlocation, pinchScale, pinchDelta and pinchVelocitylocation, rotationAngle and rotationVelocitylocationgesture.state
The current state of the gesture, using the same constants as touches:
BEGAN - the gesture was recognizedCHANGED - the gesture moved or changedENDED - the gesture finished or was cancelledA tap reports ENDED once it is recognized.
gesture.location
The location of the gesture event on the screen
gesture.translation
The translation of the gesture event relative to its starting location, with positive y pointing up
gesture.delta
The delta of the gesture event since last update
gesture.pinchScale
The scale of a pinch gesture relative to its starting distance
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
The rate of change of the pinch scale, in scale factor per second
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
The rate of change of the rotation angle, in degrees per second
gesture.touchCount
The current number of touches associated with this gesture
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)
Creates and registers a new tap gesture recognizer that will call callback(gesture) when recognized
| 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 |
gesture.tap |
gesture.tap.enabled
Enables/disables this gesture recognizer
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
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)
Creates and registers a new pan gesture recognizer that will call callback(gesture) as the pan begins, moves and ends
| 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 |
gesture.pan |
gesture.pan.enabled
Enables/disables this gesture recognizer
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
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)
Creates and registers a new pinch gesture recognizer that will call callback(gesture) when recognized
| callback | function. Function called with the gesture object when its state changes. |
gesture.pinch |
gesture.pinch.enabled
Enables/disables this gesture recognizer
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
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)
Creates and registers a new rotation gesture recognizer that will call callback(gesture) when recognized
| callback | function. Function called with the gesture object when its state changes. |
gesture.rotation |
gesture.rotation.enabled
Enables/disables this gesture recognizer
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
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)
endSee Input for key callbacks and shortcut examples.
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
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)
endSee Input for hover, scroll and pinch callbacks and pointer locking.
key.pressing(keyCode)
Queries whether the key is currently held down
| keyCode | constant. The keyCode to query |
boolean |
Is the key held down |
key.wasPressed(keyCode)
Queries whether the key went down since the previous frame
| keyCode | constant. The keyCode to query |
boolean |
Was the key pressed down this frame |
key.wasReleased(keyCode)
Queries whether the key came up since the previous frame
| keyCode | constant. The keyCode to query |
boolean |
Was the key released this frame |
key.modifiers()
Queries the current key modifiers as a bit field, which is composed of the following bit mask constants:
key.altkey.ctrlkey.cmdkey.shiftUse key.pressing(keyCode) to query individual keys such as key.leftAlt.
integer |
The modifiers currently held |
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)
| modifiers | constant. The key modifiers to query as a bit field |
boolean |
Are the key modifiers currently pressed |
press
A single key event, passed to the global keyPressed(press) and keyReleased(press) functions
press.keyCode
The key, as one of the key key code constants such as key.a or key.space
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
The text produced by the key, taking modifiers such as shift into account
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()
key.leftAlt
key.rightAlt
key.leftCtrl
key.rightCtrl
key.leftCmd
key.rightCmd
key.leftShift
key.rightShift
key.backspace
key.insert
key.delete
key.pageup
key.pagedown
key.leftbracket
key.rightbracket
key.semicolon
key.period
key.backslash
key.nonUSBackslash
key.numpad0
key.numpad1
key.numpad2
key.numpad3
key.numpad4
key.numpad5
key.numpad6
key.numpad7
key.numpad8
key.numpad9
gamepad.all
A list of all currently connected gamepads
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
True for an on-screen controller. Physical gamepads return false.
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
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
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
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
Disable on-screen controls (the default). Physical controllers remain available.
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
Use Carbide’s drawn controls. Currently supports only the left stick and A button.
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
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
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
The left shoulder button
gamepad.rightShoulder
The right shoulder button
gamepad.leftTrigger
The left trigger
gamepad.rightTrigger
The right trigger
gamepad.dpad
The directional pad
gamepad.leftStick
gamepad.rightStick
gamepad.leftStickButton
gamepad.rightStickButton
gamepad.a
gamepad.b
gamepad.x
gamepad.y
gamepad.home
gamepad.options
gamepad.touchpadButton
gamepad.touchpadSurface
gamepad.batteryLevel
The battery charge, from 0 to 1
gamepad.batteryState
The battery state, one of gamepad.charging, gamepad.discharging, gamepad.full or gamepad.unknown
gamepad.light
The color of the controller’s light, on controllers that have one
gamepad.playerIndex
The player number shown on the controller, one of gamepad.unset, gamepad.player1, gamepad.player2, gamepad.player3 or gamepad.player4
gamepad.vendorName
The name of the controller as reported by its maker
gamepad.unset
gamepad.player1
gamepad.player2
gamepad.player3
gamepad.player4
gamepad.charging
gamepad.discharging
gamepad.full
gamepad.unknown
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
A button.
gamepad.control.b
B button.
gamepad.control.x
X button.
gamepad.control.y
Y button.
gamepad.control.dpad
Directional pad.
gamepad.control.leftStick
Left stick.
gamepad.control.rightStick
Right stick.
gamepad.control.leftShoulder
Left shoulder button.
gamepad.control.rightShoulder
Right shoulder button.
gamepad.control.leftTrigger
Left trigger.
gamepad.control.rightTrigger
Right trigger.
gamepad.button
A button or trigger on a gamepad
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
true while the button is held down
gamepad.button.pressed
true only in the frame the button went down
gamepad.button.released
true only in the frame the button came up
gamepad.button.value
How far the button is pressed, from 0 to 1. Triggers report values in between
gamepad.button.touching
true while a finger rests on the button, on controllers that can sense it
gamepad.directionalPad
A stick, directional pad or touchpad surface on a gamepad
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
The direction, with each axis from -1 to 1
gamepad.directionalPad.x
gamepad.directionalPad.y
gamepad.directionalPad.left
gamepad.directionalPad.right
gamepad.directionalPad.up
gamepad.directionalPad.down
keyboard.show()
Shows the on-screen keyboard. It stays up when the screen is touched, until keyboard.hide() is called
keyboard.hide()
Hides the on-screen keyboard
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
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.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
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
The current position of the pointer as a vec2
mouse.dx
The horizontal movement of the pointer since the last frame
mouse.dy
The vertical movement of the pointer since the last frame
mouse.delta
The movement of the pointer since the last frame as a vec2
mouse.scroll
The scroll wheel or trackpad scroll amount this frame
mouse.left
The left mouse button. Trackpad clicks also count as the left button
mouse.middle
The middle mouse button
mouse.right
The right mouse button
mouse.active
Whether a mouse or trackpad is currently connected
mouse.visible
Gets or sets the visibility of the system pointer cursor
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
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
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)
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.| referenceFrame | number. The reference frame in which to track motion metrics. Can be one of the following values: |
motion.referenceFrame
Reference frame constants for motion tracking.
motion.stop()
Stop tracking motion metrics and set autoStart to false.
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
The gravity vector in the device’s reference frame. This vector is automatically rotated to follow device orientation changes.
motion.acceleration
The acceleration vector in the device’s reference frame. This vector is automatically rotated to follow device orientation changes.
motion.rotationRate
The rotation rate in the device’s reference frame. This vector is automatically rotated to follow device orientation changes.
motion.sensorLocation
Sensor location constants.
motion.heading
The heading in degrees relative to the current reference frame.
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.
motion.magnetic
Magnetic field data.
motion.magneticAccuracy
Magnetic field accuracy constants.