If you're seeing this message, it means we're having trouble loading external resources on our website.

相互吸引

``````var movers = [];

for (var i = 0; i < 5; i++) {
movers[i] = new Mover(
random(0.1, 2),
random(width),
random(height));
}

draw = function() {
background(255, 255, 255);
for (var i = 0; i < movers.length; i++) {
movers[i].update();
movers[i].display();
}
};``````
`draw()` 函数是我们需要施展一些魔术的地方。 目前，我们说：“对于每个 mover i，更新并显示自己。” 现在我们需要说的是：“对于每个mover i，被每一个mover j吸引，更新并显示自己。”
``````for (var i = 0; i < movers.length; i++) {
// 检查每个Mover
for (var j = 0; j < movers.length; j++) {
var force = movers[j].calculateAttraction(movers[i]);
movers[i].applyForce(force);
}
}

for (var i = 0; i < movers.length; i++) {
movers[i].update();
movers[i].display();
}``````

``````Mover.prototype.calculateAttraction = function(m) {
var force = PVector.sub(this.position, m.position);
var distance = force.mag();
distance = constrain(distance, 5.0, 25.0);
force.normalize();

var strength = (G * this.mass * m.mass) / (distance * distance);
force.mult(strength);
return force;
};``````

0 ⇢ 1, 2, 3, 4
1 ⇢ 0, 2, 3, 4
2 ⇢ 0, 1, 3, 4
3 ⇢ 0, 1, 2, 4

``````for (var i = 0; i < movers.length; i++) {
for (var j = 0; j < movers.length; j++) {
if (i !== j) {
var force = movers[j].calculateAttraction(movers[i]);
movers[i].applyForce(force);
}
}
}``````

“自然模拟”系列课程是由 Daniel Shiffman 的 "编程的本质" 衍生而来，基于 知识共享 著名-非商用性 3.0 本地化许可协议