Okay, here's the HTML, CSS, and JavaScript code to create a bouncing ball inside a rotating hexagon, simulating gravity and wall friction.
This example uses a circular approximation for collision detection within the hexagon for simplicity, treating the hexagon as a circle with a radius corresponding to the distance from the center to the hexagon's closest wall points.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotating Hexagon Ball</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="scene">
<div class="hexagon-container">
<div class="hexagon"></div>
<div class="ball"></div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
style.css:
body {
margin: 0;
overflow: hidden; /* Prevent scrollbars */
background-color: #1a1a1a; /* Dark background */
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
font-family: sans-serif;
color: white;
text-align: center;
}
.scene {
position: relative;
width: 400px; /* Adjust size as needed */
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
/* Container to manage hexagon size and rotation */
.hexagon-container {
--hexagon-width: 200px; /* Base size */
/* Height of a regular hexagon is width * sqrt(3)/2 */
--hexagon-height: calc(var(--hexagon-width) * 0.866);
--hexagon-radius: calc(var(--hexagon-width) / 2); /* Distance to corners */
/* Effective radius for collision (distance to flat side midpoint) */
--hexagon-collision-radius: calc(var(--hexagon-radius) * 0.866); /* ~86.6px */
width: var(--hexagon-width);
height: var(--hexagon-height);
position: relative;
animation: rotate 8s linear infinite; /* Rotate the hexagon */
}
/* The hexagon shape itself */
.hexagon {
position: absolute;
width: 100%;
height: 100%;
background-color: #444; /* Hexagon color */
/* Create the hexagon shape using clip-path */
/* Points are relative to the bounding box (width x height) */
clip-path: polygon(
50% 0%, /* Top center */
100% 25%, /* Top right */
100% 75%, /* Bottom right */
50% 100%, /* Bottom center */
0% 75%, /* Bottom left */
0% 25% /* Top left */
);
/* Center the hexagon within its container */
top: 0;
left: 0;
/* Ensure transform-origin is center for rotation */
transform-origin: center center;
}
/* The ball */
.ball {
position: absolute;
width: 30px;
height: 30px;
background-color: #ffdd57; /* Ball color */
border-radius: 50%;
/* Center the ball initially */
top: 50%;
left: 50%;
/* Translate by -50% to center based on its own size */
transform: translate(-50%, -50%);
/* Ensure ball is above the hexagon */
z-index: 10;
}
/* Animation for hexagon rotation */
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.instructions {
position: absolute;
bottom: 20px;
left: 0;
right: 0;
color: rgba(255, 255, 255, 0.7);
font-size: 0.9em;
}
script.js:
const hexagonContainer = document.querySelector('.hexagon-container');
const ballElement = document.querySelector('.ball');
const hexagonStyle = getComputedStyle(hexagonContainer);
// Physics constants
const GRAVITY = 0.4; // Acceleration due to gravity (pixels/frame^2)
const BOUNCE_FACTOR = 0.65; // Coefficient of restitution (how much velocity is kept after bounce)
const FRICTION_FACTOR = 0.99; // General slowdown factor per frame (air resistance / internal friction)
const WALL_PUSH_FACTOR = 0.3; // How much to push the ball out if it slightly overlaps the wall
// Ball state
let ball = {
x: 0, // Position relative to hexagon center
y: 0,
vx: 0, // Velocity x
vy: 0, // Velocity y
radius: ballElement.offsetWidth / 2 // Ball radius in pixels
};
// Get hexagon collision radius from CSS variable
const HEXAGON_COLLISION_RADIUS = parseFloat(hexagonStyle.getPropertyValue('--hexagon-collision-radius'));
let animationFrameId;
// Function to update ball physics and position
function updatePhysics() {
// 1. Apply Gravity
ball.vy += GRAVITY;
// 2. Apply general friction/slowdown
ball.vx *= FRICTION_FACTOR;
ball.vy *= FRICTION_FACTOR;
// 3. Update position based on velocity
ball.x += ball.vx;
ball.y += ball.vy;
// 4. Collision Detection & Response (Circular Approximation)
const distance = Math.sqrt(ball.x * ball.x + ball.y * ball.y);
const effectiveRadius = HEXAGON_COLLISION_RADIUS - ball.radius; // Space available for ball center
if (distance > effectiveRadius) {
// Collision occurred
// Calculate normalized normal vector pointing outward from center
const normalX = ball.x / distance;
const normalY = ball.y / distance;
// Resolve overlap: Move ball back to the edge
// Calculate how much it overlapped and push it back along the normal
const overlap = distance - effectiveRadius;
ball.x -= normalX * overlap * (1 + WALL_PUSH_FACTOR); // Push slightly more for stability
ball.y -= normalY * overlap * (1 + WALL_PUSH_FACTOR);
// Calculate reflection velocity
const velDotNormal = ball.vx * normalX + ball.vy * normalY;
// Reflect velocity only if the ball is moving towards the wall
if (velDotNormal < 0) {
// V_reflected = V - 2 * (V . N) * N
const reflectedVx = ball.vx - 2 * velDotNormal * normalX;
const reflectedVy = ball.vy - 2 * velDotNormal * normalY;
// Apply bounce factor (coefficient of restitution)
ball.vx = reflectedVx * BOUNCE_FACTOR;
ball.vy = reflectedVy * BOUNCE_FACTOR;
// Optional: Add slight friction on bounce (reduce velocity tangential to wall)
// This is implicitly handled a bit by BOUNCE_FACTOR < 1 and FRICTION_FACTOR
}
}
// 5. Update Ball's CSS Transform
// The CSS animation handles the hexagon's rotation.
// We apply the ball's position relative to the center using translate.
// The CSS already applies translate(-50%, -50%) for initial centering.
// We add our calculated translate values.
ballElement.style.transform = `translate(calc(-50% + ${ball.x}px), calc(-50% + ${ball.y}px))`;
}
// Main animation loop
function gameLoop() {
updatePhysics();
animationFrameId = requestAnimationFrame(gameLoop);
}
// --- Interaction ---
hexagonContainer.addEventListener('click', (event) => {
// Calculate click position relative to the hexagon's center (in its non-rotated frame)
const rect = hexagonContainer.getBoundingClientRect();
const hexCenterX = rect.left + rect.width / 2;
const hexCenterY = rect.top + rect.height / 2;
// Get click coordinates relative to the viewport
const clickX_viewport = event.clientX;
const clickY_viewport = event.clientY;
// --- Correct for Hexagon Rotation ---
// 1. Get current rotation angle (approximated from CSS animation)
// We need the actual rotation angle. Getting it reliably from CSS animation is tricky.
// A simpler way is to track it in JS, but the CSS animation runs independently.
// Let's *estimate* based on time, or apply impulse relative to current view.
// Simpler: apply impulse directly relative to the clicked point's offset from center.
// Calculate offset from center
let dx = clickX_viewport - hexCenterX;
let dy = clickY_viewport - hexCenterY;
// --- Apply Impulse ---
const impulseStrength = 1.5; // Adjust strength of the push
const angle = Math.atan2(dy, dx); // Angle of the click relative to center
// Give the ball a velocity boost in the direction of the click
ball.vx += impulseStrength * Math.cos(angle);
ball.vy += impulseStrength * Math.sin(angle);
// Make sure the ball doesn't get stuck if clicked exactly at center
if (Math.abs(ball.x) < 5 && Math.abs(ball.y) < 5) {
ball.vx += impulseStrength * Math.cos(angle);
ball.vy += impulseStrength * Math.sin(angle);
}
});
// --- Initialization ---
// Start the animation loop
animationFrameId = requestAnimationFrame(gameLoop);
// Add instructions text
const instructions = document.createElement('div');
instructions.className = 'instructions';
instructions.innerHTML = 'Click inside the hexagon to push the ball.';
document.body.appendChild(instructions);
// Cleanup on unload (optional, good practice)
window.addEventListener('unload', () => {
cancelAnimationFrame(animationFrameId);
});
Explanation:
-
HTML:
- A
.scene div acts as the overall container.
.hexagon-container holds the hexagon and is responsible for the rotation via CSS animation. It defines the size using CSS variables.
.hexagon is the visual hexagon shape created using clip-path.
.ball is the element representing the ball.
-
CSS:
- Basic styling centers everything and sets a dark background.
--hexagon-width, --hexagon-height, --hexagon-radius, --hexagon-collision-radius define the hexagon's geometry. The collision radius is set to the distance from the center to the midpoint of a flat side, which is the closest wall.
- The
.hexagon-container has the rotate animation applied.
clip-path: polygon(...) defines the hexagon shape based on the container dimensions.
- The
.ball is positioned absolutely and centered. Its transform will be updated by JavaScript.
-
JavaScript:
- State: The
ball object stores its position (x, y) relative to the center of the hexagon and its velocity (vx, vy). ball.radius is also stored.
- Constants:
GRAVITY, BOUNCE_FACTOR, and FRICTION_FACTOR control the physics simulation. HEXAGON_COLLISION_RADIUS is read from CSS.
updatePhysics():
- Applies gravity to
ball.vy.
- Applies general friction by multiplying velocities by
FRICTION_FACTOR.
- Updates
ball.x and ball.y based on velocities.
- Collision: Calculates the distance from the center. If the distance plus the ball's radius exceeds the hexagon's effective radius, a collision is detected.
- Collision Response:
- Calculates the normal vector (direction away from the center).
- Moves the ball slightly back towards the center to resolve overlap.
- Reflects the ball's velocity using the standard reflection formula .
Save these three files (index.html, style.css, script.js) in the same folder and open index.html in your web browser.