I'm pretty sure after looking through the documentation that this isn't what the framework is intended to do, but I've got a student I'm tutoring who really wants to move an object drawn on a P5 canvas using input, like using the arrow keys.
What I was able to figure out is the following:
let value = 0;
function setup() {
// Create a canvas with a specified width and height
createCanvas(400, 400);
// Fill in background color
background("blue");
}
function draw() {
background(200);
rectMode(CENTER);
translate(value, value, value);
translate(150, 150, 150)
rect(0, 0, 20, 20);
}
function keyPressed() {
while(true) {
if (keyCode == LEFT_ARROW) {
value = 20;
}
}
}
But of course, this uses an infinite loop and is therefore less than ideal. Does anyone know of a better way to achieve this?
On my system (Chrome, MacOS), keyPressed is called repeatedly if I hold the left-arrow key. Below is a really simple example. Focus into the snippet and hold down your left arrow key - observe that the xPos decreases every frame.
You need to actually do something in your keyPressed method. Right now, the value is just being assigned repeatedly, and definitely, you don't want to have an infinite loop.
For the record, according to the docs, keyPressed isn't guaranteed to work this way on all systems, so you may need more complex logic depending on what system(s) you want to run this on.
function setup() {
createCanvas(640, 360);
}
let xPos = 100;
function draw() {
background(0,0,255);
fill(255,0,0);
ellipse(xPos,50,10,10);
}
function keyPressed(event) {
if (keyCode == LEFT_ARROW) {
xPos -= 1;
} else if (keyCode == RIGHT_ARROW) {
xPos += 1;
}
// this prevents default browser behavior
event.preventDefault();
return false;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.3.3/p5.min.js"></script>
let acl;
let pos;
let value = 0;
function setup() {
acl = createVector(0,0);
pos = createVector(0,0);
// Create a canvas with a specified width and height
createCanvas(400, 400);
// Fill in background color
background("blue");
}
function draw() {
background(200);
rectMode(CENTER);
rect(pos.x, pos.y, 20, 20);
pos.add(acl);
}
function keyPressed() {
if (keyCode == LEFT_ARROW) {
acl.set(-1,0)
}
if(keyCode == RIGHT_ARROW){
acl.set(1,0)
}
}