问题
I'm trying to make a simple drawing program where the color and size of the line being drawn changes when the 'e' key is held down. However, when I try to use keyPressed
, it only executes once, resulting in a single blue dot being drawn instead of changing the whole line. Basically, what I need to know is how to make something happen when a key is held, because it only registers the press once. This is what I have so far:
function keyTyped() {
if (key === 'e') {
if (mouseY < 417) {
fill(0,0,255,100);
ellipse(mouseX,mouseY,5,5);
}
}
}
instead of
function draw() {
if (mouseY < 417) {
noStroke();
fill(0,100);
ellipse(mouseX,mouseY,20,20);
}
}
回答1:
You could just check from the draw()
function, like this:
function draw() {
if (keyIsPressed && key == 'e') {
noStroke();
fill(0,100);
ellipse(mouseX,mouseY,20,20);
}
}
Or you could create a variable that tracks whether the key is being pressed. Set it to true
from the keyPressed()
function, and set it to false
in the keyReleased()
function. Then check the variable in the draw()
function.
More info can be found in the reference.
来源:https://stackoverflow.com/questions/46351604/how-to-make-something-happen-when-a-key-is-held-down-in-p5-js