小球碰撞是一个常见的物理模拟问题,在JavaScript中可以通过计算小球的运动轨迹和碰撞检测来实现。下面是一个简单的示例代码,展示了如何实现两个小球在网页上的碰撞效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ball Collision</title>
<style>
#container {
position: relative;
width: 800px;
height: 600px;
border: 1px solid black;
}
.ball {
position: absolute;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="container">
<div id="ball1" class="ball" style="width: 50px; height: 50px; background-color: red; left: 50px; top: 50px;"></div>
<div id="ball2" class="ball" style="width: 50px; height: 50px; background-color: blue; left: 200px; top: 50px;"></div>
</div>
<script>
const container = document.getElementById('container');
const ball1 = document.getElementById('ball1');
const ball2 = document.getElementById('ball2');
let x1 = 50, y1 = 50, dx1 = 2, dy1 = 2;
let x2 = 200, y2 = 50, dx2 = -2, dy2 = 2;
function update() {
// Update ball positions
x1 += dx1;
y1 += dy1;
x2 += dx2;
y2 += dy2;
// Check for collisions with container walls
if (x1 + 50 >= container.clientWidth || x1 <= 0) dx1 = -dx1;
if (y1 + 50 >= container.clientHeight || y1 <= 0) dy1 = -dy1;
if (x2 + 50 >= container.clientWidth || x2 <= 0) dx2 = -dx2;
if (y2 + 50 >= container.clientHeight || y2 <= 0) dy2 = -dy2;
// Check for collision between balls
const dx = x2 - x1;
const dy = y2 - y1;
const distance = Math.sqrt(dx * dx + dy * dy);
const minDistance = 50 + 50; // Sum of radii
if (distance < minDistance) {
// Swap velocities
[dx1, dx2] = [dx2, dx1];
[dy1, dy2] = [dy2, dy1];
}
// Update ball positions in DOM
ball1.style.left = `${x1}px`;
ball1.style.top = `${y1}px`;
ball2.style.left = `${x2}px`;
ball2.style.top = `${y2}px`;
requestAnimationFrame(update);
}
update();
</script>
</body>
</html>
requestAnimationFrame
优化动画效果,减少不必要的DOM操作。通过上述代码和解释,你应该能够理解并实现基本的小球碰撞效果。如果有更复杂的需求或问题,可以进一步优化代码逻辑。
Tencent Serverless Hours 第15期
云+社区技术沙龙[第14期]
云+社区沙龙online [国产数据库]
云+社区沙龙online [国产数据库]
Lowcode Talk
腾讯技术创作特训营第二季第5期
云+社区沙龙online [新技术实践]
云+社区沙龙online [技术应变力]
领取专属 10元无门槛券
手把手带您无忧上云