Okay, this is a fun challenge involving canvas drawing, basic physics (gravity, velocity), and collision detection (wall-ball and ball-ball).
We'll build this using the HTML <canvas> element and JavaScript.
Here's the single HTML/JS file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotating Hexagon with Bouncing Balls</title>
<style>
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #222;
margin: 0;
overflow: hidden; /* Prevent scrollbars */
font-family: Arial, sans-serif;
color: #eee;
}
canvas {
background-color: #333;
border: 2px solid #555;
box-shadow: 0 0 15px rgba(0, 255, 255, 0.7);
}
h1 {
color: #00ffcc;
margin-bottom: 20px;
text-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
}
</style>
</head>
<body>
<h1>Rotating Hexagon</h1>
<canvas id="gameCanvas"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// --- Configuration ---
const CANVAS_SIZE = 700; // Width and Height
canvas.width = CANVAS_SIZE;
canvas.height = CANVAS_SIZE;
const HEX_RADIUS = CANVAS_SIZE * 0.4;
const HEX_CENTER_X = CANVAS_SIZE / 2;
const HEX_CENTER_Y = CANVAS_SIZE / 2;
const HEX_ROTATION_SPEED = 0.005; // Radians per frame
const NUM_BALLS = 10;
const BALL_RADIUS = 15;
const GRAVITY = 0.3; // Pixels per frame per frame
const BOUNCE_FACTOR = 0.8; // How much energy is retained after a bounce (0 to 1)
const FRICTION = 0.99; // Damping for velocity over time
const MIN_VELOCITY_THRESHOLD = 0.1; // Balls stop moving if velocity is below this
// --- Global Variables ---
let hexRotation = 0;
let balls = [];
let lastTime = 0;
// --- Helper Functions (Vector Math) ---
function dist(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
}
function normalize(vector) {
const mag = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
if (mag === 0) return { x: 0, y: 0 };
return { x: vector.x / mag, y: vector.y / mag };
}
function dot(v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
}
// --- Ball Class ---
class Ball {
constructor(x, y, radius, color, mass) {
this.x = x;
this.y = y;
this.vx = (Math.random() - 0.5) * 5;
this.vy = (Math.random() - 0.5) * 5;
this.radius = radius;
this.color = color;
this.mass = mass;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.strokeStyle = '#000';
ctx.lineWidth = 1;
ctx.stroke();
}
update(deltaTime) {
// Apply gravity
this.vy += GRAVITY * deltaTime;
// Apply friction
this.vx *= FRICTION;
this.vy *= FRICTION;
// Stop if velocity is very low
if (Math.abs(this.vx) < MIN_VELOCITY_THRESHOLD && Math.abs(this.vy) < MIN_VELOCITY_THRESHOLD && this.y + this.radius > CANVAS_SIZE * 0.9) { // Simple check if on 'ground'
this.vx = 0;
this.vy = 0;
return; // Skip movement if stopped
}
// Update position
this.x += this.vx * deltaTime;
this.y += this.vy * deltaTime;
}
}
// --- Hexagon Drawing & Geometry ---
function getHexagonVertices(centerX, centerY, radius, rotation) {
const vertices = [];
for (let i = 0; i < 6; i++) {
const angle = (Math.PI / 3) * i + rotation; // Start at 0 degrees (right)
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
vertices.push({ x: x, y: y });
}
return vertices;
}
function drawHexagon(vertices) {
ctx.beginPath();
ctx.moveTo(vertices[0].x, vertices[0].y);
for (let i = 1; i < vertices.length; i++) {
ctx.lineTo(vertices[i].x, vertices[i].y);
}
ctx.closePath();
ctx.strokeStyle = '#00FFFF'; // Cyan
ctx.lineWidth = 3;
ctx.stroke();
}
// --- Collision Detection & Resolution ---
// Ball-Wall Collision (Line Segment to Circle)
function checkWallCollision(ball, vertices) {
for (let i = 0; i < vertices.length; i++) {
const p1 = vertices[i];
const p2 = vertices[(i + 1) % vertices.length]; // Next vertex, wraps around for last edge
// Vector representing the wall segment
const wallVec = { x: p2.x - p1.x, y: p2.y - p1.y };
// Vector from wall start to ball center
const ballVec = { x: ball.x - p1.x, y: ball.y - p1.y };
// Project ballVec onto wallVec to find the closest point on the line
let t = dot(ballVec, wallVec) / dot(wallVec, wallVec);
// Clamp t to ensure the closest point is on the segment
t = Math.max(0, Math.min(1, t));
// Closest point on the segment
const closestX = p1.x + t * wallVec.x;
const closestY = p1.y + t * wallVec.y;
const distance = dist(ball.x, ball.y, closestX, closestY);
if (distance < ball.radius) {
// Collision detected!
// Calculate the collision normal (vector from closest point to ball center)
const normal = normalize({ x: ball.x - closestX, y: ball.y - closestY });
// Separate the ball from the wall to prevent sticking
const overlap = ball.radius - distance;
ball.x += normal.x * overlap;
ball.y += normal.y * overlap;
// Reflect velocity
const speed = Math.sqrt(ball.vx * ball.vx + ball.vy * ball.vy);
const currentVelocityVector = { x: ball.vx, y: ball.vy };
// Calculate component of velocity along the normal
const vn = dot(currentVelocityVector, normal);
// If moving away from wall, don't reflect
if (vn > 0) continue;
// Reflected velocity along normal
const newVn = -vn * BOUNCE_FACTOR;
// Get tangential velocity component (perpendicular to normal)
const tangent = { x: -normal.y, y: normal.x };
const vt = dot(currentVelocityVector, tangent);
// Combine new normal velocity with original tangential velocity
ball.vx = newVn * normal.x + vt * tangent.x;
ball.vy = newVn * normal.y + vt * tangent.y;
// Apply some additional damping if needed
ball.vx *= BOUNCE_FACTOR;
ball.vy *= BOUNCE_FACTOR;
}
}
}
// Ball-Ball Collision (Circle to Circle)
function checkBallCollision(ball1, ball2) {
const dx = ball2.x - ball1.x;
const dy = ball2.y - ball1.y;
const distance = Math.sqrt(dx * dx + dy * dy);
const minDistance = ball1.radius + ball2.radius;
if (distance < minDistance && distance !== 0) {
// Collision detected!
const normal = { x: dx / distance, y: dy / distance };
const tangent = { x: -normal.y, y: normal.x };
// Separate the balls to prevent sticking
const overlap = minDistance - distance;
const separationVector = { x: normal.x * overlap, y: normal.y * overlap };
ball1.x -= separationVector.x * 0.5;
ball1.y -= separationVector.y * 0.5;
ball2.x += separationVector.x * 0.5;
ball2.y += separationVector.y * 0.5;
// Project velocities onto normal and tangent axes
const v1n = dot({ x: ball1.vx, y: ball1.vy }, normal);
const v1t = dot({ x: ball1.vx, y: ball1.vy }, tangent);
const v2n = dot({ x: ball2.vx, y: ball2.vy }, normal);
const v2t = dot({ x: ball2.vx, y: ball2.vy }, tangent);
// Calculate new normal velocities (1D elastic collision formula)
const m1 = ball1.mass;
const m2 = ball2.mass;
const v1n_final = (v1n * (m1 - m2) + 2 * m2 * v2n) / (m1 + m2);
const v2n_final = (v2n * (m2 - m1) + 2 * m1 * v1n) / (m1 + m2);
// Apply bounce factor to normal velocities
const new_v1n = v1n_final * BOUNCE_FACTOR;
const new_v2n = v2n_final * BOUNCE_FACTOR;
// Reconstruct final velocities
ball1.vx = new_v1n * normal.x + v1t * tangent.x;
ball1.vy = new_v1n * normal.y + v1t * tangent.y;
ball2.vx = new_v2n * normal.x + v2t * tangent.x;
ball2.vy = new_v2n * normal.y + v2t * tangent.y;
}
}
// --- Initialization ---
function init() {
// Create balls
for (let i = 0; i < NUM_BALLS; i++) {
const angle = Math.random() * Math.PI * 2;
const spawnRadius = HEX_RADIUS * 0.5; // Spawn inside hexagon but not too close to walls
const x = HEX_CENTER_X + spawnRadius * Math.cos(angle);
const y = HEX_CENTER_Y + spawnRadius * Math.sin(angle);
const color = `hsl(${Math.random() * 360}, 70%, 60%)`; // Random vibrant color
const mass = BALL_RADIUS; // Simple mass proportional to radius
balls.push(new Ball(x, y, BALL_RADIUS, color, mass));
}
}
// --- Animation Loop ---
function animate(currentTime) {
const deltaTime = (currentTime - lastTime) / 16.66; // Normalize to 60fps (1000ms / 60 frames ≈ 16.66ms)
lastTime = currentTime;
// Clear canvas
ctx.clearRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
// Update hexagon rotation
hexRotation += HEX_ROTATION_SPEED * deltaTime;
const currentHexagonVertices = getHexagonVertices(HEX_CENTER_X, HEX_CENTER_Y, HEX_RADIUS, hexRotation);
// Update and draw balls, check collisions
for (let i = 0; i < balls.length; i++) {
const ball = balls[i];
ball.update(deltaTime);
checkWallCollision(ball, currentHexagonVertices);
// Check ball-ball collisions (only check each pair once)
for (let j = i + 1; j < balls.length; j++) {
checkBallCollision(ball, balls[j]);
}
ball.draw();
}
// Draw hexagon
drawHexagon(currentHexagonVertices);
requestAnimationFrame(animate);
}
// Start the game
init();
requestAnimationFrame(animate);
</script>
</body>
</html>