好的,这个挑战很有趣!我们将使用HTML、CSS和JavaScript来模拟这个物理动画。
核心思路:
- HTML结构: 两个主要的容器,分别代表地球和月球环境。每个容器内有一个六边形和两个小球(虽然需求是两个球在 一个 六边形里,但为了方便区分地球和月球,我们做成两个独立的六边形,每个里面一个球)。
- CSS样式:
- 创建六边形:使用
clip-path属性可以很方便地创建六边形。
- 创建小球:简单的圆形。
- 六边形旋转:使用CSS
@keyframes动画让六边形持续旋转。
- JavaScript物理模拟:
- 主循环: 使用
requestAnimationFrame创建动画循环。
- 时间步长: 计算
deltaTime以确保物理模拟在不同帧率下表现一致。
- 小球状态: 维护每个小球的位置 (
x, y)、速度 (vx, vy)。
- 物理定律:
- 重力: 持续增加
vy(向下)。地球和月球的重力加速度不同。
- 摩擦力: 每次更新速度时,减小
vx和vy。
- 弹力/碰撞:
- 检测小球是否与六边形的任何一面发生碰撞。
- 六边形旋转,所以需要将小球的坐标转换到六边形的局部坐标系,或者更简单地,旋转六边形各个边的法向量。
- 当碰撞发生时,反转小球在法向量方向上的速度分量,并乘以恢复系数(
restitution)来模拟弹跳。
- 处理渗透:如果小球穿透了墙壁,需要将其推回墙壁之外。
- 更新UI: 根据物理计算的结果,使用
transform: translate()更新小球的DOM位置。
代码实现:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>旋转六边形小球物理动画</title>
<style>
body {
display: flex;
justify-content: space-around;
align-items: center;
min-height: 100vh;
margin: 0;
background-color: #222;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
color: #eee;
overflow: hidden; /* Prevent scrollbars */
}
.container {
text-align: center;
padding: 20px;
border-radius: 10px;
background-color: #333;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
}
h2 {
margin-bottom: 25px;
color: #ccc;
}
.hexagon-wrapper {
position: relative;
width: 250px; /* 六边形的外接圆直径 */
height: 250px;
display: flex;
justify-content: center;
align-items: center;
margin: 0 auto;
border: 2px solid rgba(255, 255, 255, 0.3); /* 外层容器的细边框 */
border-radius: 50%; /* 模拟圆形容器,但里面是六边形 */
}
.hexagon {
position: absolute;
width: 90%; /* 六边形实际大小,相对于wrapper */
height: 90%;
background-color: transparent;
border: 3px solid #00f; /* 六边形边框 */
box-sizing: border-box; /* 边框包含在尺寸内 */
clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
animation: rotateHexagon 10s linear infinite; /* 旋转动画 */
}
/* 旋转动画 */
@keyframes rotateHexagon {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.ball {
position: absolute;
width: 30px; /* 小球直径 */
height: 30px;
border-radius: 50%;
background-color: #ff6347; /* 小球颜色 */
box-shadow: 0 0 10px rgba(255, 99, 71, 0.7);
/* 将小球初始位置居中,然后通过JS的transform: translate来移动 */
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* 确保初始时小球中心对齐容器中心 */
}
</style>
</head>
<body>
<div class="container">
<h2>地球环境</h2>
<div class="hexagon-wrapper">
<div class="hexagon earth-hexagon"></div>
<div class="ball earth-ball"></div>
</div>
</div>
<div class="container">
<h2>月球环境</h2>
<div class="hexagon-wrapper">
<div class="hexagon moon-hexagon"></div>
<div class="ball moon-ball"></div>
</div>
</div>
<script>
// 获取DOM元素
const earthHexagon = document.querySelector('.earth-hexagon');
const earthBall = document.querySelector('.earth-ball');
const moonHexagon = document.querySelector('.moon-hexagon');
const moonBall = document.querySelector('.moon-ball');
// 物理常量
const EARTH_GRAVITY = 98.1; // 地球重力加速度 (像素/秒^2)
const MOON_GRAVITY = EARTH_GRAVITY * 0.165; // 月球重力约为地球的1/6 (像素/秒^2)
const FRICTION_FACTOR = 0.99; // 摩擦力系数,每次速度更新的衰减
const RESTITUTION = 0.7; // 恢复系数 (弹力), 0-1, 1为完全弹性碰撞
const BALL_RADIUS = earthBall.offsetWidth / 2; // 小球半径
const HEXAGON_WRAPPER_SIZE = earthHexagon.parentElement.offsetWidth; // 六边形容器的宽度/高度
const HEXAGON_RADIUS_EFFECTIVE = (HEXAGON_WRAPPER_SIZE * 0.9) / 2; // 六边形自身有效半径 (中心到顶点距离)
// 六边形边框的厚度 (用于碰撞检测)
const HEXAGON_BORDER_THICKNESS = 3;
// 计算六边形的内切圆半径(apothem),即从中心到边的垂直距离
// 对于边长为s的六边形,半径R=s。内切圆半径 a = R * cos(30 deg)
const APOTHEM = HEXAGON_RADIUS_EFFECTIVE * Math.cos(Math.PI / 6);
// 小球状态类
class Ball {
constructor(element, gravity) {
this.element = element;
this.gravity = gravity;
this.x = 0; // 初始X位置 (相对于六边形中心)
this.y = 0; // 初始Y位置 (相对于六边形中心)
this.vx = (Math.random() - 0.5) * 50; // 初始X速度 (随机小幅左右运动)
this.vy = (Math.random() - 0.5) * 50; // 初始Y速度 (随机小幅上下运动)
}
// 更新小球物理状态
update(deltaTime, hexagonAngle) {
// 应用重力
this.vy += this.gravity * deltaTime;
// 更新位置
this.x += this.vx * deltaTime;
this.y += this.vy * deltaTime;
// 碰撞检测与响应 (与六边形的六条边)
const hexCenterToBallX = this.x;
const hexCenterToBallY = this.y;
// 六边形有6条边,每条边的法向量相对于垂直方向旋转60度(PI/3弧度)
// 且每条边都有一个到中心的固定距离 (APOTHEM)
for (let i = 0; i < 6; i++) {
// 计算当前边的法向量角度
// 初始角度(0度)指向右侧,逆时针旋转
// 第一条边(右下)的法向量指向外侧的 (-cos(30), -sin(30))
// 顺时针旋转,所以是 i * PI/3
const normalAngle = hexagonAngle + (i * Math.PI / 3);
// 法向量分量 (指向六边形内部)
const normalX = Math.cos(normalAngle);
const normalY = Math.sin(normalAngle);
// 小球中心到边的距离 (沿法向量方向)
// dot product of (ball position vector) and (normal vector)
const distToCenterAlongNormal = hexCenterToBallX * normalX + hexCenterToBallY * normalY;
// 计算小球到六边形内部边界的距离
// APOTHEM 是中心到边的距离。
// 边界向内缩了HEXAGON_BORDER_THICKNESS / 2 (因为边框是双向的)
const effectiveApothem = APOTHEM - HEXAGON_BORDER_THICKNESS / 2;
const penetrationDepth = effectiveApothem - (distToCenterAlongNormal + BALL_RADIUS);
if (penetrationDepth > 0) { // 发生碰撞或有渗透
// 将小球推回到边界外
this.x += normalX * penetrationDepth;
this.y += normalY * penetrationDepth;
// 速度反射
const dotProduct = this.vx * normalX + this.vy * normalY;
this.vx -= (1 + RESTITUTION) * dotProduct * normalX;
this.vy -= (1 + RESTITUTION) * dotProduct * normalY;
// 摩擦力 (沿切线方向)
// 切线向量是法向量旋转90度
const tangentX = -normalY;
const tangentY = normalX;
const tangentialSpeed = this.vx * tangentX + this.vy * tangentY;
this.vx = this.vx - tangentialSpeed * tangentX + tangentialSpeed * tangentX * FRICTION_FACTOR;
this.vy = this.vy - tangentialSpeed * tangentY + tangentialSpeed * tangentY * FRICTION_FACTOR;
// 简单摩擦力 (适用于所有速度分量)
this.vx *= FRICTION_FACTOR;
this.vy *= FRICTION_FACTOR;
}
}
// 速度衰减 (空气阻力或滚动摩擦)
this.vx *= FRICTION_FACTOR;
this.vy *= FRICTION_FACTOR;
}
// 渲染小球位置
render() {
// transform: translate() 是相对于元素自身中心点的偏移
this.element.style.transform = `translate(calc(-50% + ${this.x}px), calc(-50% + ${this.y}px))`;
}
}
// 创建小球实例
const earthBallSim = new Ball(earthBall, EARTH_GRAVITY);
const moonBallSim = new Ball(moonBall, MOON_GRAVITY);
let lastTime = 0;
// 获取CSS动画的当前旋转角度
function getHexagonRotation(element) {
const style = window.getComputedStyle(element);
const transform = style.transform;
if (transform === 'none') {
return 0;
}
// Parse the 2D transformation matrix
// matrix(a, b, c, d, tx, ty)
const matrix = new DOMMatrixReadOnly(transform);
// angle = atan2(b, a)
return Math.atan2(matrix.m12, matrix.m11); // m12 is 'b', m11 is 'a'
}
function animate(currentTime) {
const deltaTime = (currentTime - lastTime) / 1000; // 转换为秒
lastTime = currentTime;
if (isNaN(deltaTime) || deltaTime > 0.1) { // 避免初始或大跳跃的deltaTime
requestAnimationFrame(animate);
return;
}
// 获取当前六边形旋转角度
const earthHexAngle = getHexagonRotation(earthHexagon);
const moonHexAngle = getHexagonRotation(moonHexagon);
// 更新和渲染地球小球
earthBallSim.update(deltaTime, earthHexAngle);
earthBallSim.render();
// 更新和渲染月球小球
moonBallSim.update(deltaTime, moonHexAngle);
moonBallSim.render();
requestAnimationFrame(animate);
}
// 启动动画
requestAnimationFrame(animate);
</script>
</body>
</html>
解释:
-
HTML 结构:
body 使用 flexbox 将两个模拟环境水平居中排列。
container 是每个环境的包装器,包含标题、六边形容器和小球。
hexagon-wrapper:一个圆形容器,用来确保六边形和小球的定位都在一个相对的、有边界的区域内。
hexagon:实际的六边形元素,使用 clip-path 创建形状,并用 CSS animation 实现连续旋转。
ball:小球元素。
-
CSS 样式:
clip-path: polygon(...) 是创建六边形的关键。
@keyframes rotateHexagon 定义了从0度到360度的旋转动画。
position: absolute; 和 left: 50%; top: 50%; transform: translate(-50%, -50%); 用来将小球的中心精确对齐到其父容器 (hexagon-wrapper) 的中心。后续 JavaScript 中的 transform: translate() 将在此基础上进行偏移。
-
JavaScript 物理模拟:
Ball 类: 封装了每个小球的状态(位置、速度)和行为(更新物理、渲染)。
- 物理常量:
EARTH_GRAVITY 和 MOON_GRAVITY 是关键的区别。FRICTION_FACTOR 控制速度衰减,RESTITUTION 控制碰撞后的弹跳程度。
HEXAGON_RADIUS_EFFECTIVE 和 APOTHEM:
HEXAGON_RADIUS_EFFECTIVE 是从六边形中心到其顶点的距离。
APOTHEM 是从六边形中心到其任何一条边的垂直距离,它等于 R * cos(30°),其中 R 是六边形的半径(中心到顶点)。这个值是碰撞检测中计算距离的关键。
getHexagonRotation(element) 函数: 这是获取 CSS transform 动画当前旋转角度的巧妙之处。它通过解析计算后的 transform 样式属性(一个CSS Matrix)来提取旋转角度。
update(deltaTime, hexagonAngle) 方法:
- 重力:
this.vy += this.gravity * deltaTime; 简单地将重力加速度累加到垂直速度上。
- 位置更新:
this.x += this.vx * deltaTime; 和 this.y += this.vy * deltaTime; 根据速度更新位置。
- 碰撞检测: 这是最复杂的部分。
- 循环遍历六边形的六条边。
- 对于每一条边,计算其在当前六边形旋转角度下的法向量 (
normalX, normalY)。
distToCenterAlongNormal 计算小球中心沿该法向量方向到六边形中心的投影距离。
penetrationDepth:如果这个距离加上小球半径大于六边形的 APOTHEM(即小球已经穿透了墙壁),则表示发生了碰撞。
- 碰撞响应:
现在,你将看到两个独立的模拟器,一个在地球重力下,小球会快速下落并剧烈反弹;另一个在月球重力下,小球会缓慢下落并进行更轻微的弹跳,同时六边形都在持续旋转。