基于《代码本色》0-5章的拓展
参考《代码本色》的第0~4章内容及其实例程序,创作一组编程习作,体现随机行为及牛顿力学。
1.使用高斯分布生成随机的小球
效果图:
不加高斯分布时生成的随机小球效果图:
由此可见,高斯分布后小球会从中间慢慢向外散开的生成,效果很好看,但是代码很简单,只要将x、y坐标通过高斯随机分布计算出来就可以。
关键代码:
//x坐标和y坐标的高斯分布
float x = randomGaussian()*60 + width/2;
float y = randomGaussian()*60 + height/2;
float r = random(10,100); //10-100的随机半径
...
fill(random(128, 255), random(0,20), random(0,50), random(0, 100)); //随机颜色填充
2.使用向量控制小球的运动
效果图:
参考《代码本色》的例子,每次运行后都会生成跟前一次大小不同,颜色不同的四个小球,如下:
关键代码:
1.定义一个Ball类,用PVector对象定义位置、速度,再将半径、颜色等值,设置为随机。后面用面向对象的点语法从PVector对象中分别获取它的x变量和y变量。
class Ball {
PVector position;
PVector velocity;
float ra = random(10,100);
int r = int(random(255));
int g = int(random(255));
int b = int(random(255));
int a = int(random(255));
Ball() {
position = new PVector(random(50,200), random(50,50));
velocity = new PVector(random(2,3),random(3,5));
}
void update() {
position.add(velocity);
if ((position.x > width) || (position.x < 0)) {
velocity.x = velocity.x * -1;
}
if ((position.y > height) || (position.y < 0)) {
velocity.y = velocity.y * -1;
}
}
void display() {
noStroke();
fill(r,g,b);
ellipse(position.x, position.y, ra, ra);
}
}
2.在vectors里调用这个类里的函数。
Ball a;
Ball b;
Ball c;
Ball d;
void setup() {
size(400, 400);
a = new Ball();
b = new Ball(