Pi.js provides a range of input functions that allow you to handle user input from the keyboard, mouse, touch screen, and gamepads. These functions make it easy to create engaging, interactive experiences that respond to user input in real-time. Whether you’re building a simple game or a complex demo, pi.js provides the tools you need to create dynamic, responsive user interfaces. In this article, we’ll explore the various input functions provided by pi.js and how they can be used to create engaging games and demos.
input
The input function prompts the user to type input from the keyboard and press enter when done. It takes an optional parameter that specifies the message to display to the user. The function returns a promise that resolves with the text entered by the user, with a number when the prompt is numeric, or with null when the prompt is cancelled. You can cancel an input prompt using the cancelInput function.
$.screen( "300x200" );
askQuestions();
async function askQuestions() {
let name = await $.input( "What is your name? " );
let age = await $.input( "How old are you? ", null, null, true, true, false, 3 );
$.print( "Your name is " + name + " you are " + age + " years old." );
}inKey
The inKey function reads any keys currently being pressed by the keyboard. It returns a string representing the key being pressed. This function is useful for games that require the player to hold down keys to move continuously.
$.screen( "300x200" );
requestAnimationFrame( run );
function run() {
let keys = $.inKey();
$.cls();
$.print( "Press any key" );
for( const key in $.inKey() ) {
$.print( "--------------------------" );
$.print( "key: " + keys[ key ].key );
$.print( "location: " + keys[ key ].location );
$.print( "code: " + keys[ key ].code );
}
requestAnimationFrame( run );
}onKey
The onKey function triggers an event when a key is pressed down or released. It takes three parameters: the key code or key name to listen for, the mode which can be up or down, and a function to call when the event is triggered.
$.screen( "300x200" );
$.print( "Press any key." );
$.print( "Press q to stop" );
$.onKey( "any", "down", keyPress );
$.onKey( "q", "down", stopPress, true );
// Key press function
function keyPress( key ) {
$.print( "You pressed " + key.key + "!" );
}
// Stop key press function
function stopPress() {
$.print( "You pressed q! Stopping." );
$.offKey( "any", "down", keyPress );
}inMouse
The inMouse function returns an object with properties x and y, and buttons representing the current position of the mouse cursor on the screen and the state of the buttons. It returns null before the first mouse event.
$.screen( "300x200" );
requestAnimationFrame( run );
let tail = [];
let c = 7;
let pal = $.getPal();
function run() {
$.cls();
const mouse = $.inMouse();
// There is no mouse data before the first mouse event
if( mouse !== null && mouse.buttons > 0 ) {
c = ( c + 1 ) % pal.length;
if( c === 1 ) {
c = 1;
}
}
if( mouse !== null ) {
tail.push( [ mouse.lastX, mouse.lastY, c ] );
if( tail.length > 50 ) {
tail.shift();
}
}
let lastPt = null;
for( const pt of tail ) {
if( lastPt !== null ) {
$.setColor( pt[ 2 ] );
$.line( lastPt[ 0 ], lastPt[ 1 ], pt[ 0 ], pt[ 1 ] );
}
lastPt = pt;
}
requestAnimationFrame( run );
}onMouse
The onMouse function triggers an event when the mouse is moved or a button is pressed down or released. It requires two parameters: the event type to listen for (e.g. “up”, “down”, “move”), and a function to call when the event is triggered. There are also three optional parameters (e.g. once, hitBox, and customData).
$.screen( "300x200" );
$.print( "Move mouse to paint screen, click to stop." );
$.onMouse( "move", mouseMove );
$.onMouse( "up", mouseStop, true );
// Mouse move function
function mouseMove( data ) {
$.setPosPx( data.x, data.y );
let pos = $.getPos();
$.setPos( pos.col, pos.row );
$.setColor( 8 );
$.print( "+", true );
}
// Mouse stop function
function mouseStop() {
$.setColor( 14 );
let pos = $.getPos();
$.setPos( pos.col - 4, pos.row );
$.print( "Stopped!", true );
$.offMouse( "move", mouseMove );
}onWheel
The onWheel function triggers an event when the mouse wheel is turned or a trackpad is scrolled over the screen. It requires one parameter: a function to call when the event is triggered. The function receives an object with the properties x and y for the position of the mouse cursor, and deltaX and deltaY for the amount scrolled. While a wheel function is registered, the page does not scroll when the wheel is turned over the screen. You can remove a wheel function using the offWheel function.
$.screen( "300x200" );
let radius = 40;
drawCircle();
$.onWheel( wheelTurn );
// Wheel turn function grows or shrinks the circle
function wheelTurn( data ) {
radius = Math.min( Math.max( radius - data.deltaY / 20, 5 ), 90 );
drawCircle();
}
// Draw circle function
function drawCircle() {
$.cls();
$.print( "Turn the mouse wheel to resize." );
$.circle( 150, 100, Math.floor( radius ) );
}inTouch
The inTouch function returns an array of touch objects representing the current touch points on the screen.
$.screen( "300x200" );
requestAnimationFrame( run );
function run() {
const touches = $.inTouch();
for( const touch of touches ) {
$.print( `Touch ${touch.id} at ${touch.x}, ${touch.y}` );
}
requestAnimationFrame( run );
}onTouch
The onTouch function triggers an event when a touch point is added, moved, or removed from the screen. It takes two parameters: the event type to listen for (e.g. “down”, “move”, “up”), and a function to call when the event is triggered. The function runs once for each touch and receives the touch that changed in an array.
$.screen( "300x200" );
$.print( "Touch to paint screen, touch end to stop." );
$.onTouch( "move", touchMove );
$.onTouch( "up", touchStop, true );
// Touch move function receives touchData and optional customData
function touchMove( touchData, customData ) {
$.setPosPx( touchData[ 0 ].x, touchData[ 0 ].y );
const pos = $.getPos();
$.setPos( pos.col, pos.row );
$.setColor( 8 );
$.print( "+", true );
}
// touch stop function receives touchData and optional customData
function touchStop( touchData, customData ) {
$.setColor( 14 );
const pos = $.getPos();
$.setPos( pos.col - 4, pos.row );
$.print( "Stopped!", true );
$.offTouch( "move", touchMove );
}inGamepad
The inGamepad function returns an array of gamepad objects representing the currently connected gamepads.
$.screen( "300x200" );
$.setColor( 15 );
let x = 150;
let y = 100;
let c = 7;
requestAnimationFrame( run );
function run() {
let factor = 1.5;
let pads = $.inGamepad();
$.cls();
$.setColor( c );
if( pads.length > 0 ) {
if( pads[ 0 ].getButtonJustPressed( 0 ) || pads[ 0 ].getButtonJustPressed( 1 ) ) {
c += 1;
if( c > 240 ) {
c = 1;
}
}
x = Math.min( Math.max( x + pads[ 0 ].axes[ 0 ] * factor, 0 ), 299 );
y = Math.min( Math.max( y + pads[ 0 ].axes[ 1 ] * factor, 0 ), 199 );
$.circle( Math.floor( x ), Math.floor( y ) , 10 );
$.pset( Math.floor( x ), Math.floor( y ) );
} else {
$.print( "Connect gamepad and move axes to begin" );
}
requestAnimationFrame( run );
}onGamepad
The onGamepad function triggers an event when a gamepad is connected or disconnected. It takes two parameters: the mode which can be connect or disconnect, and a function to call when the event is triggered. The connect function also runs for each gamepad that is already connected. Please note that browsers do not report a gamepad until one of its buttons is pressed or one of its axes is moved. You can remove a gamepad function using the offGamepad function.
$.screen( "300x200" );
$.print( "Connect a gamepad and press a button." );
$.onGamepad( "connect", padConnect );
$.onGamepad( "disconnect", padDisconnect );
// Gamepad connect function
function padConnect( pad ) {
$.print( "Gamepad " + pad.index + " connected." );
}
// Gamepad disconnect function
function padDisconnect( data ) {
$.print( "Gamepad " + data.index + " disconnected." );
}vibrateGamepad
The vibrateGamepad function rumbles a gamepad. It requires two parameters: the index of the gamepad and the length of the rumble in milliseconds. There are also two optional parameters that set the strength of the strong and weak motors from 0 to 1. The function returns true if the rumble was started, or false if the gamepad or the browser does not support it.
$.screen( "300x200" );
$.print( "Press a gamepad button to rumble." );
requestAnimationFrame( run );
function run() {
let pads = $.inGamepad();
if( pads.length > 0 && pads[ 0 ].getButtonJustPressed( 0 ) ) {
if( $.vibrateGamepad( pads[ 0 ].index, 200, 1, 0.5 ) ) {
$.print( "Rumble!" );
} else {
$.print( "This gamepad cannot rumble." );
}
}
requestAnimationFrame( run );
}inPress
The inPress function works with both mouse and touch events and returns an object with properties x and y representing the current position of the mouse cursor or touch point. It returns null before the first mouse or touch event.
$.screen( "300x200" );
$.setPinchZoom( false );
requestAnimationFrame( run );
let tail = [];
function run() {
const press = $.inPress();
$.cls();
// Draw press indicator; there is no press data before the first event
if( press !== null && press.buttons > 0 ) {
$.setColor( 15 );
$.circle( press.x, press.y, 10 );
// Draw trail while dragging
if( press.action === "move" ) {
tail.push( [ press.x, press.y ] );
if( tail.length > 50 ) {
tail.shift();
}
let lastPt = null;
for( const pt of tail ) {
if( lastPt !== null ) {
$.setColor( 7 );
$.line( lastPt[ 0 ], lastPt[ 1 ], pt[ 0 ], pt[ 1 ] );
}
lastPt = pt;
}
}
// Show input type
$.setColor( 2 );
$.print( `Input: ${press.type}` );
} else {
$.print( "Press and drag to draw" );
tail = [];
}
requestAnimationFrame( run );
}onPress
The onPress function triggers an event when a mouse button is pressed or released, or a touch point is added or removed from the screen.
$.screen( "300x200" );
$.print(
"Move mouse or touch to paint screen," +
" click/touch up to stop."
);
$.onPress( "move", pressMove );
$.onPress( "up", pressStop, true );
// Press move function
function pressMove( data ) {
$.setPosPx( data.x, data.y );
var pos = $.getPos();
$.setPos( pos.col, pos.row );
$.setColor( 8 );
$.print( "+", true );
}
// Press stop function
function pressStop() {
$.setColor( 14 );
var pos = $.getPos();
$.setPos( pos.col - 4, pos.row );
$.print( "Stopped!", true );
$.offPress( "move", pressMove );
}onClick
The onClick function triggers an event when the left mouse button or a touch is pressed and released inside the same area. It requires one parameter: a function to call when the event is triggered. There are also three optional parameters (e.g. once, hitBox, and customData). The hitBox sets the area that can be clicked, and if it is left out the whole screen is used. You can remove a click function using the offClick function.
$.screen( "300x200" );
let count = 0;
const box = { "x": 100, "y": 80, "width": 100, "height": 40 };
drawBox();
$.onClick( boxClick, false, box );
// Box click function
function boxClick() {
count += 1;
drawBox();
}
// Draw box function
function drawBox() {
$.cls();
$.print( "Click the box." );
$.print( "Clicks: " + count );
$.rect( box );
}Please checkout the Pi.js Reference page to see a full listing of input functions.