Processing 与键盘结合
1、使用键盘来改变输出的图形
输入代码:
void setup() {
size(240, 120);
smooth();
}
void draw() {
background(204);
line(20, 20, 220, 100);
if (keyPressed) {
//如果按下按键,显示直线
line(220, 20, 20, 100);
}
}

2、输出效果:
当按下键盘任意按键时,窗口会变成两条直线;
如果没有按键按下,窗口中只会显示一条直线。

3、显示按下的按键
输入代码:
void setup() {
size(120, 120);
textSize(64);
textAlign(CENTER);
}
void draw() {
background(0);
text(key, 60, 80);
}

4、输出结果:
当有按键按下时,窗口会显示出按下的相应按键

5、Processing 识别不同的字符
输入代码:
void setup() {
size(120, 120);
smooth();
}
void draw() {
background(204);
if (keyPressed) {
if ((key == 'h') || (key == 'H')) {
line(30, 60, 90, 60);
}
if ((key == 'n') || (key == 'N')) {
line(30, 20, 90, 100);
}
}
line(30, 20, 30, 100);
line(90, 20, 90, 100);
}
输出效果如下图所示
当没有按键按下时,输出为两条竖线
当按下 n 或 N 时,输出为 N
当按下 h 或 H 时,输出为 H

6、通过方向键,移动显示的图形
输入代码:
int x = 215;
void setup() {
size(480, 120);
}
void draw() {
if (keyPressed && (key == CODED)) { // If it’s a coded key
if (keyCode == LEFT) { // If it’s the left arrow
x--;
} else if (keyCode == RIGHT) { // If it’s the right arrow
x++;
}
}
rect(x, 45, 50, 50);
}
输出效果为当按下方向键的左键和右键时,窗口中显示的图形会向相应的方向移动


7、图形跟随鼠标运动,并且在单击左键时,图形改变图形的尺寸
输入代码:
float x = 60;
float y = 440;
int radius = 45;
int bodyHeight = 160;
int neckHeight = 70;
float easing = 0.02;
void setup() {
size(360, 480);
smooth();
strokeWeight(2);
ellipseMode(RADIUS);
}
void draw() {
int targetX = mouseX;
x += (targetX - x) * easing;
if (mousePressed) {
neckHeight = 16;
bodyHeight = 90;
} else {
neckHeight = 70;
bodyHeight = 160;
}
float ny = y - bodyHeight - neckHeight - radius;
background(204);
stroke(102);
line(x+12, y-bodyHeight, x+12, ny);
line(x+12, ny, x-18, ny-43);
line(x+12, ny, x+42, ny-99);
line(x+12, ny, x+78, ny+15);
noStroke();
fill(102);
ellipse(x, y-33, 33, 33);
fill(0);
rect(x-45, y-bodyHeight, 90, bodyHeight-33);
fill(0);
ellipse(x+12, ny, radius, radius);
fill(255);
ellipse(x+24, ny-6, 14, 14);
fill(0);
ellipse(x+24, ny-6, 3, 3);
}

