书名:Processing互动编程艺术
作者:谭亮
出版社:电子工业出版社
出版时间:2011-06
ISBN:9787121134630
一、norm()把指定数从指定范围映射到0.0~1.0
norm(value, start, stop)
start:开始值
stop:结束值
value:int或float值原理:
(value-start)/(stop-start)
float x=norm(60, 50, 100); //将0.2赋值给x
float y=norm(45, 50, 100) ; //将-0.1赋值给y
float z=norm(110, 50, 100) ; //将1.2赋值给z
二、飞机类

void setup()
{ size(800,600); //设置窗口的大小
planes=new Plane[10]; //初始化飞机数组,设置飞机数量为10
bombers=new Bomber[10]; //初始化轰炸机数组,设置轰炸机数量为10
for (int i=0; i<planes.length; i++)
{ //创建飞机对象
planes[i]=new Plane();
}
for (int i=0; i<bombers.length; i++)
{ //初始化每个轰炸机对象
bombers[i]=new Bomber();
}
}
void draw()
{ background(204); //背景颜色
randomSeed(47); //随机数种子
for (int i=0; i<planes.length; i++)
{ planes[i].update(); //更新每架飞机的位置
planes[i].DisplayPlane(random(255), random(255), random(255));
// 画出飞机,颜色随机
}
for (int i=0; i<bombers.length; i++)
{ bombers[i].update();
bombers[i].DisplayPlane(random(255), random(255), random(255));
}
}
Plane[] planes; //声明一个存放飞机对象的数组
Bomber[] bombers; //声明一个存放轰炸机对象的数组
class Plane
{ PVector position; //创建位置向量
PVector speed; //创建速度向量
Plane()
{ //飞机类构造函数
float x=random(width); //飞机初始坐标,在画面范围内随机获得
float y=random(height);
position= new PVector(x, y); //将左边赋值给位置向量
speed= PVector.random2D(); //速度向量的方向随机获得
speed.setMag(random(5,10));
// 速度向量的大小为5~10随机获得
}
void update()
{ //更新飞机位置的函数
position.add(speed); //在原有的位置向量上加上速度向量
boundaryrel(); //调用飞机碰到边缘后反弹函数
}
void DisplayPlane(float R, float G, float B)
{ //画飞机的函数,R、G、B三个参数表示飞机的颜色
float x=position.x; //飞机的左边由位置向量获得
float y=position.y;
fill(R, G, B); //填充飞机的颜色
beginShape(); //开始绘制图形
vertex(x, y);
vertex(x-10, y+30);
vertex(x-10, y+50);
vertex(x-40, y+80);
vertex(x-40, y+85);
vertex(x-10, y+85);
vertex(x-10, y+90);
vertex(x-20, y+96);
vertex(x-20, y+100);
vertex(x+20, y+100);
vertex(x+20, y+96);
vertex(x+10, y+90);
vertex(x+10, y+85);
vertex(x+40, y+85);
vertex(x+40, y+80);
vertex(x+10, y+50);
vertex(x+10, y+30);
vertex(x, y);
endShape(); //结束绘制图形
}
void boundaryrel(){
// 如果飞机x坐标小于0,把x坐标设置为0,速度x分量反向
if(position.x<0)
{ if(position.x<0)
{ position.x=0;
speed.x*=-1;
}
else if(position.x>width)
{ //如果飞机x坐标大于画布宽,把x坐标设置为宽,速度x分量反向
position.x=width;
speed.x*=-1;
}
if (position.y<0)
{ //如果飞机y坐标小于0,把x坐标设置为0,速度y分量反向
position.y=0;
speed.y*=-1;
}
else if(position.y>height)
{ //如果飞机y坐标大于画布高,把y坐标设置为高,速度y分量反向
position.y=height;
speed.y*=-1;
}
}
}
}
class Bomber extends Plane //轰炸机对象,继承飞机向量
{
void DisplayPlane(float R, float G, float B) //覆写绘制飞机函数
{
float x=position.x;
float y=position.y;
fill(R, G, B);
beginShape();
vertex(x, y);
vertex(x-40, y+37);
vertex(x-30, y+30);
vertex(x-20, y+37);
vertex(x-10, y+30);
vertex(x, y+37);
vertex(x+10, y+30);
vertex(x+20, y+37);
vertex(x+30, y+30);
vertex(x+40, y+37);
vertex(x+50, y+30);
vertex(x, y);
endShape();
}
Bomber(){ //构造函数,轰炸机的速度大小为2~5的随机数
speed.setMag(random(2,5));
}
}