search
HomeWeb Front-endJS TutorialDetailed explanation of p5.js keyboard interaction

This article mainly introduces to you the keyboard interaction of the p5.js introductory tutorial. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

1. Keywords and functions related to keyboard interaction

keyIsPressed: Keyword, true when the key is pressed, otherwise false

keyCode: keyword, used to determine which key is pressed

keyPressed(): function, triggered once when the key is pressed

keyReleased(): function, key Triggered once when released

keyIsDown(): function, returns true when the specified key is pressed, otherwise false

The following is a more comprehensive case, using wsad and zxcv to control the movement of the ball :


var x=200; 
var y=200; 
var speed=2; 
 
function setup() {  
 createCanvas(400, 400); 
}  
 
function draw() {  
 background(220); 
 ellipse(x,y,20,20); 
 if(keyIsPressed){ 
  //持续触发 
  //字母用小写 
  if(key=='a'){ 
   x-=speed; 
  } 
  if(key=='d'){ 
   x+=speed; 
  } 
 } 
 if(keyIsDown(87)){ 
  //持续触发 
    //使用keyCode 
  //87即w 
  y-=speed; 
 } 
 if(keyIsDown(83)){ 
  //持续触发 
  //使用keyCode 
  //83即s 
  y+=speed; 
 } 
} 
 
function keyPressed(){ 
 //按键按下时触发一次 
 //字母用大写 
  if(key=='Z'){ 
  x-=20; 
 } 
 if(key=='X'){ 
  x+=20; 
 } 
} 
 
function keyReleased(){ 
 //按键松开时触发一次 
 //字母用大写 
  if(key=='C'){ 
  y-=20; 
 } 
 if(key=='V'){ 
  y+=20; 
 } 
}

View the effect: http://alpha.editor.p5js.org/full/S1YQvEFIZ

2. key and keyCode

The following example will output the key and keyCode of the key you pressed on the screen. You can use this method to quickly find the keyCode when writing a program:


function setup() {  
 createCanvas(400, 400); 
}  
 
function draw() {  
 background(220); 
 textAlign(CENTER); 
 textSize(30); 
 if(keyIsPressed){ 
  text(key,200,180);  
  text(keyCode,200,220);  
 } 
}

View the effect: http://alpha.editor.p5js.org/full/rkZ2TVFLW

The above is the detailed content of Detailed explanation of p5.js keyboard interaction. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Functional Programming in JavaScript: Core ConceptsFunctional Programming in JavaScript: Core ConceptsJul 23, 2025 am 02:03 AM

Pure functions ensure that the same input always gets the same output without side effects, making it easier to test and concurrent processing; 2. Use immutable data to avoid hidden bugs by creating new versions instead of modifying the original data, especially in React/Redux; 3. High-order functions allow functions to be passed and combined, such as map/filter/reduce to rely on this feature to achieve flexible logic; 4. Function combinations connect small functions like pipelines to improve modularity and readability; 5. Use map/filter/reduce to replace loops to implement declarative, secure and easy to chain call code, ultimately making JavaScript code more reliable and easy to maintain.

How to get the current date and time in JavaScript?How to get the current date and time in JavaScript?Jul 23, 2025 am 01:39 AM

The methods to get the current date and time in JavaScript are as follows: 1. Use newDate() to create a date object to get the full date and time; 2. Use getFullYear(), getMonth(), getDate() and other methods to obtain year, month, day and time units respectively; 3. Use string splicing or padStart() to achieve custom formatted output; 4. Use toLocaleString() to output in local format, and you can also specify language and region. The core of these methods is to operate the Date object and pay attention to problems such as starting from 0 in the month, so as to flexibly respond to different needs.

Exploring the Deno JavaScript RuntimeExploring the Deno JavaScript RuntimeJul 23, 2025 am 01:28 AM

DenoisamodernruntimeforJavaScriptandTypeScriptofferingbuilt-inTypeScriptsupport,asecurepermissionmodel,andaURL-basedmodulesystem.1.ItrunsTypeScriptnativelywithoutextraconfiguration.2.Itenforcessecuritythroughopt-inpermissionslike--allow-readand--allo

How to use the nullish coalescing operator (??) in JavaScript?How to use the nullish coalescing operator (??) in JavaScript?Jul 23, 2025 am 01:27 AM

The ?? operator should be used when dealing with a default value scenario with null or undefined, as it returns the right default value only if it is null or undefined on the left. 1. Unlike ||, ?? will not treat empty strings, 0, false values such as false values as invalid; 2. It is often used to set the default value of function parameters, such as functiongreet(user){console.log(${user??'sranger'});}; 3. It is suitable for safely taking values from objects, such as constusername=data.user??'Anonymous'; 4. It can be used with optional chains, such as user.profile?.

JavaScript Concurrency with SharedArrayBuffer and AtomicsJavaScript Concurrency with SharedArrayBuffer and AtomicsJul 23, 2025 am 01:23 AM

SharedArrayBuffer and Atomics are key tools in JavaScript for multithreaded shared memory and synchronous operations. 1. SharedArrayBuffer allows multiple threads to access the same piece of memory, which is suitable for data sharing between the main thread and WebWorker; 2. Atomics provides atomic operations such as load, store, add, wait and notify to ensure thread safety; 3. Using SharedArrayBuffer requires the server to enable COOP and COEP headers, and some environments such as old browsers or privacy modes do not support it; 4. In actual development, it is recommended to use Promise or async/aw first.

How to check if an array includes a value in JavaScript?How to check if an array includes a value in JavaScript?Jul 23, 2025 am 01:16 AM

There are three ways to check whether an array contains a certain value in JavaScript: one is to use the includes() method, which returns a boolean value to indicate whether the specified element exists, such as arr.includes(valueToFind, fromIndex); the second is to use the indexOf() method to determine whether the return value is -1 to achieve stronger compatibility detection; the third is to use some() or find() for object arrays to compare by fields, because include() cannot correctly compare the reference types.

JavaScript Prototype-Based Object Creation PatternsJavaScript Prototype-Based Object Creation PatternsJul 23, 2025 am 01:14 AM

JavaScript object creation method is based on prototype rather than class. Constructor Prototype combination mode defines instance properties through constructors and defines shared methods for prototypes, such as functionPerson(name){this.name=name;}Person.prototype.sayHello=function(){console.log("Hello,I'm" this.name);};constp1=newPerson("Alice");p1.sayHello(); Factory function mode encapsulates the logic of the return object, such as fu

Advanced JavaScript Functional Composition TechniquesAdvanced JavaScript Functional Composition TechniquesJul 23, 2025 am 01:10 AM

TowritecleanerandmoremaintainableJavaScriptcodethroughfunctionalcomposition,usepoint-freestyletoeliminateunnecessaryarguments,curryfunctionsforflexiblereusebycreatingpartiallyappliedfunctions,handleasyncoperationsbywrappingthemorusinganasync-awarecom

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.