如果需要连续运行,就需要在draw(){}中写下代码
void draw() {
// 控制台显示帧数
println("I'm drawing");
println(frameCount);
}
在draw()函数中的代码会一直运行下去,直到你关闭窗口,每一次执行draw()为一帧(frame)默认的帧率是60,可以修改。
println()函数输出了文本,和当前的帧率,frameCount变量
为了完成循环的draw()函数,processing还有一个setup()函数,在程序开始的时候运行一遍
void setup() {
println("I'm starting");
}
void draw() {
println("I'm running");
}
当代码运行时,控制台会输出:
I'm starting
I'm running
I'm running
。。。。。
当按下运行按钮,控制台上会先输出数字“I’m starting”,并且不断地输出“I’m running”,直到你按下暂停按钮或是关闭窗口。
被 setup 函数用大括号包裹的代码,只会执行一次。而draw函数内的,则会不断地循环执行
由于这种特性,setup往往会用于初始化环境属性,如屏幕宽高,背景颜色,各种变量的赋值。而draw函数里面常常放绘图函数,以产生不断变化的图像。
1、引入库
2、全局变量
3、setup()函数执行一次
4、draw()函数持续执行
int x = 280;
int y = -100;
int diameter = 380;
void setup() {
size(480, 120);
fill(102);
}
void draw() {
background(204);
ellipse(x, y, diameter, diameter);
}
我们再看下面这个例子
跟随鼠标
void setup() {
size(480, 120);
fill(0, 102);
noStroke();
}
void draw() {
ellipse(mouseX, mouseY, 9, 9);
}
void setup() {
size(480, 120);
fill(0, 102);
noStroke();
}
void draw() {
background(204);
ellipse(mouseX, mouseY, 9, 9);
}
background()函数会清空屏幕,所以一定要保证它被放在draw()函数中,并且在其他函数之前,否则,画上的形状会被清空。
连续作画:
mouseX和mouseY,保持当前鼠标坐标值
pmouseX和pmouseY 保持上一帧鼠标的位置。
void setup() {
size(480, 120);
strokeWeight(4);
stroke(0, 102);
}
void draw() {
line(mouseX, mouseY, pmouseX, pmouseY);
}
设置连续厚度,用鼠标移动速度表示线的厚度
void setup() {
size(480, 120);
stroke(0, 102);
}
void draw() {
float weight = dist(mouseX, mouseY, pmouseX, pmouseY);
strokeWeight(weight);
line(mouseX, mouseY, pmouseX, pmouseY);
}
轻随:
稍微落后于鼠标
float x;
float easing = 0.01;
void setup() {
size(220, 120);
}
void draw() {
float targetX = mouseX;
x += (targetX - x) * easing;
ellipse(x, 40, 12, 12);
println(targetX + " : " + x);
}
那么x变量的值总是越来越接近targetX,追上的速度由easing决定,范围0~1
把轻随和设置宽度结合
float x;
float y;
float px;
float py;
float easing = 0.05;
void setup() {
size(480, 120);
stroke(0, 102);
}
void draw() {
float targetX = mouseX;
x += (targetX - x) * easing;
float targetY = mouseY;
y += (targetY - y) * easing;
float weight = dist(x, y, px, py);
strokeWeight(weight);
line(x, y, px, py);
py = y;
px = x;
}
点击鼠标
- 本文固定链接: http://iprocessing.cn/2017/11/09/献给processing爱好者的教程【9】-响应【卡卡】/
- 转载请注明: 卡萨布兰卡 于 Processing编程艺术 发表
《献给Processing爱好者的教程【9】—响应【卡卡】》有 2 条评论