目录
序章 随机游走
实验结果

应用的技术
①概率和非均匀分布 绘制了一个小球使他有50%的概率向着鼠标所在的方向移动。
②perlin噪声 如果小球没有向着鼠标运动(另外的50%概率),那么他就使用噪声noise()产生随机数值使小球随机移动一步。
实验代码
Walker w;
float tx=0;
float ty=10000;
void setup() {
size(640,360);
w = new Walker();
background(255);
}
void draw() {
w.step();
w.display();
}
class Walker {
float x;
float y;
Walker() {
x = width / 2;
y = height / 2;
}
void display() {
stroke(100,200,200);
ellipse(x,y,16,16);
}
void step() {
float r = random(1);
if(r<0.5){
//使得小球向鼠标运动的概率是0.5
//小球向着鼠标方向移动
if((x<mouseX) && (y<mouseY)){
x++;
y++;
}
else if((x<mouseX) && (y>mouseY)){
x++;
y--;
}
else if((x>mouseX) && (y>mouseY)){
x--;
y--;
}
else if((x>mouseX) && (y<mouseY)){
x--;
y++;
}
}
else if(r>0.5){
x = x + noise(tx);//perlin噪声
y = y + noise(ty);
tx+=0.01;
ty+=0.01;
}
}
}
第一章 向量
实验结果

应用的技术
做了一个类似弹球的程序,当小球碰到鼠标小球就会被弹起,如果把鼠标移走,小球就会自然下落,当碰到窗口的边缘时也会被弹起。
①向量的加法 小球即时的位置=(原来的位置.x+速度,原来的位置.y+速度)
②向量运动的速度和加速度 小球运动时设置了大小方向恒定的加速度使得小球下落运动的速度越来越快。
实验代码
Mover mover;
void setup() {
size(300,300);
mover = new Mover();
}
void draw() {
background(255);
mover.update();
mover.checkEdges();
mover.display();
}
class PVector {
float x;
float y;
PVector(float x_,float y_) {
x = x_;
y = y_;
}
void add(PVector v) {
x = x + v.x;
y = y + v.y;
}
void sub(PVector v) {
x = x - v.x;
y = y - v.y;
}
void mult(float n) {
x = x * n;
y = y * n;
}
void div(float n) {
x = x / n;
y = y / n;
}
float mag() {
return sqrt(x * x + y * y);
}
void normalize() {
float m = mag();
if(m != 0) {
div(m);
}
}
void limit(float max) {
if(mag() > max) {
normalize();
mult(max);
}
}
}
class Mover {
PVector location;
PVector velocity;
PVector acceleration;
float topspeed;
Mover() {
location = new PVector(width/2,0);
velocity = new PVector(random(-2,2),random(-2,2));//初始速度随机
acceleration = new PVector(-0.001,0.1);//加速度大小方向恒定
topspeed = 10;
}
void update() {
velocity.add(acceleration);//更新速度
velocity.limit(topspeed);
location.add(velocity); //更新位置
}
void display() {
stroke(100,200,200);
fill(100,200,200);
ellipse(location.x,location.y,20,20);
}
void checkEdges() {
//小球碰到鼠标后反弹
if((location.x > mouseX) || (location.x < 0)

这篇博客通过processing展示了从随机游走、向量运动、力的作用到粒子系统的编程实践。作者详细解释了每个实验的技术应用,如概率分布、Perlin噪声、向量加法、速度和加速度、外力、阻力、弹力以及粒子受力等,通过实例代码加深理解。

4111

被折叠的 条评论
为什么被折叠?



