【Processing入门】第四章:响应互动

时间:2022-11-21 20:11:07

(1) mouseX,mouseY控制图形的移动

void setup()
{
background(200);
size(300,300);
smooth();
}
void draw()
{

fill(255,255,0);
rect(mouseX,mouseY,50,50);
}


还可以控制图形的大小形状

void setup()
{
size(300,300);
smooth();
}

void draw()
{
background(200);
stroke(0);
float d=dist(mouseX,mouseY,150,150);
strokeWeight(d/15);
fill(255);
ellipse(150,150,d*2,d);
strokeWeight(d/20);
fill(255,200,0);
ellipse(150,150,d,d);
fill(0);
noStroke();
ellipse(150,150,d/3,d/3);
}

【Processing入门】第四章:响应互动

 

(2)pmouseX,pmouseY也是一对系统变量,是指相对当前鼠标坐标点的上一个坐标位置

void setup()
{
size(300,300);
strokeWeight(5);
smooth();
stroke(255,0,80,100);
background(0);
}

void draw()
{
float k=dist(mouseX,mouseY,pmouseX,pmouseY);
strokeWeight(k);
 if(mousePressed)
 {
   line(mouseX,mouseY,pmouseX,pmouseY);
 }
}

【Processing入门】第四章:响应互动

 


(3)mousePressed

void setup()
{
size(300,300);
strokeWeight(5);
smooth();
stroke(255,0,80,100);
background(0);
}

void draw()
{

}

void mousePressed()
{
stroke(0);
fill(255,255,0);
ellipse(mouseX,mouseY,25,25);
}
等价于
<p>void setup(){  size(300,300);  strokeWeight(5);  smooth();  stroke(255,0,80,100);  background(0);}</p><p>void draw(){  if(mousePressed)  {  stroke(0);  fill(255,255,0);  ellipse(mouseX,mouseY,25,25);  }}</p>
 

【Processing入门】第四章:响应互动

(4)mouseMoved,mouseDragged

void setup()
{
size(300,300);
background(255);
stroke(0,50);
smooth();
}
void draw()
{

}

void mouseMoved()
{
rectMode(CENTER);
fill(255,255,0,50);
rect(mouseX,mouseY,50,50);
}


void mouseDragged()
{
fill(255,100,0,50);
ellipse(mouseX,mouseY,50,50);
}

【Processing入门】第四章:响应互动

void setup()
{
size(300,300);
smooth();
background(204);
rectMode(CENTER);
}

void draw()
{
if(mousePressed)
{
if(mouseButton == LEFT)
{
fill(255);
}
else if(mouseButton == CENTER)
{
fill(0);
}
else
{
fill(100);
}
rect(mouseX,mouseY,50,50);
}
}

【Processing入门】第四章:响应互动

 

(5)键盘响应

按击键响应,可以使用void keyPressed(),也可以使用if(keyPressed)。用系统变量指定特定按键,当key为CODED时表示功能键,使用keyCode指定具体的功能键。

void setup()
{
size(300,300);
smooth();
strokeWeight(10);
strokeCap(SQUARE);
}

void draw()
{
background(200);
if(keyPressed)
{
if(key == 'a')
{
fill(255,0,0);
rect(100,100,100,100);
}

if(key==CODED && keyCode == UP)
{
fill(255,255,0);
rect(100,100,100,100);
}


}
}

(6)随机random

random(),用于产生特定范围的随机数,比如random(1,4)

 

(7)限制constrain()

constrain(value,min,max),value指要限定的变量值

constrain(mouseX,100,400);