# 21、《每周一点canvas动画》——万有引力

### 1.万有引力

force = G * m1 * m2 / distance^2

force = m1 * m2 / distance^2

### 2.粒子

   

### 2.加入碰撞检测

function move (partA, i) {
partA.x += partA.vx;
partA.y += partA.vy;
for (var partB, j = i + 1; j < numParticles; j++) {
partB = particles[j];
checkCollision(partA, partB); //碰撞检测
gravitate(partA, partB); //万有引力
}
}

### 3.太阳系

sun.x = canvas.width/2;
sun.y = canvas.height/2;
sun.mass = 10000;
particles.push(sun);

 earth.x = canvas.width/2+300;
earth.y = canvas.height/2;
earth.mass = 1;
earth.vy = 5.8;
earth.name = "地球";

 partA.vx += ax/partA.mass;    //加速度作用于速度
partA.vy += ay/partA.mass;
partB.vx -= ax/partB.mass;
partB.vy -= ay/partB.mass;


### 4.粒子花园

if (dist < minDist) {
context.save();
context.strokeStyle = "rgba(255,255,255,.3)";
context.beginPath();
context.moveTo(ballA.x, ballA.y);
context.lineTo(ballB.x, ballB.y);
context.closePath();
context.stroke();
context.restore();
}

### 5.总结

function gravitate(partA, partB){
var dx = partB.x - partA.x;
var dy = partB.y - partA.y;
var distQ = dx*dx + dy*dy;
var dist = Math.sqrt(distQ);
var F = (partA.mass * partB.mass)/distQ;

var ax = F * dx/dist;
var ay = F * dy/dist;

partA.vx += ax/partA.mass;
partA.vy += ay/partA.mass;
partB.vx -= ax/partB.mass;
partB.vy -= ay/partB.mass;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120