書(shū)名:代碼本色:用編程模擬自然系統(tǒng)
作者:Daniel Shiffman
譯者:周晗彬
ISBN:978-7-115-36947-5
目錄
2.5 制造外力
3幼驶、示例代碼2-2
- Mover類
不同點(diǎn)主要集中在兩個(gè)方面——質(zhì)量和applyForce()函數(shù)的實(shí)現(xiàn) - 在數(shù)組中創(chuàng)建100個(gè)Mover對(duì)象希俩。
- 在setup()函數(shù)中用循環(huán)對(duì)這些對(duì)象進(jìn)行初始化搏色。
- 在構(gòu)造函數(shù)中添加幾個(gè)參數(shù),讓它變得更靈活。
物體的質(zhì)量和初始位置就不再是硬性編碼的數(shù)值了烁挟,我們可以通過(guò)構(gòu)造函數(shù)來(lái)確定它們
??
Mover[] movers = new Mover[20];
void setup() {
size(640,360);
for (int i = 0; i < movers.length; i++) {
movers[i] = new Mover(random(0.1,4),0,0);
}
}
void draw() {
background(255);
for (int i = 0; i < movers.length; i++) {
PVector wind = new PVector(0.01,0);
PVector gravity = new PVector(0,0.1);
movers[i].applyForce(wind);
movers[i].applyForce(gravity);
movers[i].update();
movers[i].display();
movers[i].checkEdges();
}
}
mover.pde
class Mover {
PVector position;
PVector velocity;
PVector acceleration;
float mass;
color c;
Mover(float m, float x , float y) {
mass = m;
position = new PVector(x,y);
velocity = new PVector(0,0);
acceleration = new PVector(0,0);
c = color(random(255),random(255),random(255));
}
void applyForce(PVector force) {
PVector f = PVector.div(force,mass);
acceleration.add(f);
}
void update() {
velocity.add(acceleration);
position.add(velocity);
acceleration.mult(0);
}
void display() {
stroke(0);
strokeWeight(2);
//fill(0,127);
fill(c);
ellipse(position.x,position.y,mass*16,mass*16);
}
void checkEdges() {
if (position.x > width) {
position.x = width;
velocity.x *= -1;
} else if (position.x < 0) {
velocity.x *= -1;
position.x = 0;
}
if (position.y > height) {
velocity.y *= -1;
position.y = height;
}
}
}
請(qǐng)注意:在上圖中挥转,小圓到達(dá)窗口右側(cè)比大圓更快,這是因?yàn)榧铀俣?力除以質(zhì)量钥组,
質(zhì)量越大输硝,加速度越小。