js实现重力
JavaScript 实现重力效果
在 JavaScript 中实现重力效果通常用于游戏开发或动画场景,涉及物体下落、弹跳等物理模拟。以下是核心实现方法:
基础重力模拟
定义重力加速度常量(通常为正值,向下方向),并应用于物体的垂直速度:
const gravity = 0.5; // 重力加速度值
let velocityY = 0; // 初始垂直速度
let positionY = 0; // 初始垂直位置
function applyGravity() {
velocityY += gravity; // 速度受重力影响增加
positionY += velocityY; // 更新位置
}
边界检测与反弹
添加地面碰撞检测,实现物体触地反弹(能量损失模拟):

const groundHeight = 400; // 地面高度
const bounceFactor = 0.7; // 反弹系数(0-1)
function checkBoundary() {
if (positionY > groundHeight) {
positionY = groundHeight;
velocityY = -velocityY * bounceFactor; // 反弹时速度反向并衰减
}
}
完整动画循环
通过 requestAnimationFrame 实现连续动画帧:
function animate() {
applyGravity();
checkBoundary();
// 更新物体渲染位置(例如DOM元素或Canvas绘制)
object.style.top = `${positionY}px`;
requestAnimationFrame(animate);
}
animate();
高级优化技巧
-
时间补偿:根据帧间隔时间(deltaTime)调整计算,避免帧率波动导致速度异常:

let lastTime = 0; function animate(currentTime) { const deltaTime = (currentTime - lastTime) / 1000; // 转换为秒 velocityY += gravity * deltaTime; lastTime = currentTime; requestAnimationFrame(animate); } -
空气阻力:添加速度衰减模拟更真实的下落:
const airResistance = 0.99; velocityY *= airResistance; // 每帧速度衰减
实际应用示例(Canvas)
在 Canvas 中绘制受重力影响的小球:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let ball = { x: 100, y: 50, radius: 20, vx: 2, vy: 0 };
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ball.vy += gravity;
ball.y += ball.vy;
// 底部碰撞检测
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius;
ball.vy *= -bounceFactor;
}
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fill();
requestAnimationFrame(draw);
}
draw();
通过调整参数如 gravity、bounceFactor 和初始速度,可以模拟不同材质的物体运动特性。






