js实现重力
实现重力的基本思路
在JavaScript中模拟重力效果通常涉及物体受重力影响下落、反弹或与其他物体交互的物理过程。核心是通过更新物体的位置和速度来模拟加速度、重力和碰撞。
基础重力模拟
创建一个物体并使其受重力影响下落,需要定义物体的位置、速度和加速度。重力加速度通常为正值(向下)。

let position = 0;
let velocity = 0;
const gravity = 0.5;
function update() {
velocity += gravity;
position += velocity;
console.log(position);
requestAnimationFrame(update);
}
update();
添加地面碰撞
物体下落到底部时需要反弹或停止。通过检测位置是否超出边界并反转速度实现反弹效果。
let position = 0;
let velocity = 0;
const gravity = 0.5;
const ground = 300;
function update() {
velocity += gravity;
position += velocity;
if (position > ground) {
position = ground;
velocity *= -0.8; // 反弹并损失部分能量
}
console.log(position);
requestAnimationFrame(update);
}
update();
使用Canvas可视化
将重力效果可视化到Canvas中,绘制一个圆形并模拟其下落和反弹。

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let position = 50;
let velocity = 0;
const gravity = 0.5;
const ground = canvas.height - 50;
const radius = 20;
function update() {
velocity += gravity;
position += velocity;
if (position > ground) {
position = ground;
velocity *= -0.8;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(canvas.width / 2, position, radius, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
requestAnimationFrame(update);
}
update();
多物体重力交互
模拟多个物体之间的重力交互(如万有引力),需要计算物体间的距离和引力方向。
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const objects = [
{ x: 100, y: 100, vx: 0, vy: 0, mass: 10, radius: 10 },
{ x: 300, y: 200, vx: 0, vy: 0, mass: 20, radius: 15 }
];
const G = 0.1; // 引力常数
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < objects.length; i++) {
for (let j = 0; j < objects.length; j++) {
if (i === j) continue;
const dx = objects[j].x - objects[i].x;
const dy = objects[j].y - objects[i].y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance > 0) {
const force = G * objects[i].mass * objects[j].mass / (distance * distance);
const fx = force * dx / distance;
const fy = force * dy / distance;
objects[i].vx += fx / objects[i].mass;
objects[i].vy += fy / objects[i].mass;
}
}
objects[i].x += objects[i].vx;
objects[i].y += objects[i].vy;
ctx.beginPath();
ctx.arc(objects[i].x, objects[i].y, objects[i].radius, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
}
requestAnimationFrame(update);
}
update();
优化性能
对于复杂场景,可以通过以下方式优化性能:
- 限制计算精度(如忽略远距离物体的引力)。
- 使用空间分区算法(如四叉树)减少不必要的计算。
- 避免频繁的DOM操作,优先使用Canvas或WebGL渲染。
以上方法提供了从基础到进阶的重力模拟实现,适用于游戏开发、动画效果或物理模拟场景。






