📜  p5 keypressed (1)

📅  最后修改于: 2023-12-03 15:18:11.483000             🧑  作者: Mango

p5 keyPressed

p5.js is a JavaScript library that aims to make coding accessible for artists, designers, educators, and beginners. One of the core functions of p5.js is the ability to handle user interactions such as keyboard presses, mouse clicks, and touch events. In this tutorial, we will focus on how to use the keyPressed function in p5.js.

The keyPressed Function

The keyPressed function is a built-in function in p5.js that gets called whenever a key on the keyboard is pressed. You can use it to perform any action or update any variable in your program based on which key was pressed.

Here is an example of how to use the keyPressed function:

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  textAlign(CENTER, CENTER);
  textSize(50);
  text(key, width/2, height/2);  // display the last key pressed
}

function keyPressed() {
  console.log(key);  // output the last key pressed to the console
}

In this example, whenever a key is pressed, the keyPressed function will be called and the key value will be logged to the console.

Key Codes

Each key on the keyboard has a unique key code that identifies it. You can use these key codes in your keyPressed function to perform different actions based on which key was pressed.

Here is a list of some common key codes:

  • LEFT_ARROW: 37
  • UP_ARROW: 38
  • RIGHT_ARROW: 39
  • DOWN_ARROW: 40
  • SPACE: 32
  • ENTER: 13

You can find a full list of key codes on the p5.js reference page.

Here is an example of how to use key codes in your keyPressed function:

function keyPressed() {
  if (keyCode === LEFT_ARROW) {
    // move the object to the left
  } else if (keyCode === RIGHT_ARROW) {
    // move the object to the right
  } else if (keyCode === UP_ARROW) {
    // move the object up
  } else if (keyCode === DOWN_ARROW) {
    // move the object down
  }
}

In this example, if the left arrow key is pressed, the object will move to the left. If the right arrow key is pressed, the object will move to the right. The same goes for the up and down arrow keys.

Conclusion

The keyPressed function in p5.js is a powerful tool for handling user interactions and creating interactive programs. By using key codes, you can perform different actions based on which key is pressed. With this knowledge, you can create all sorts of fun and interactive projects using p5.js!