html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ball in Rotating Hexagon</title>
<style>
body {
margin: 0;
padding: 20px;
background: #1a1a1a;
color: white;
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
}
canvas {
border: 2px solid #333;
background: #000;
}
.controls {
margin-top: 20px;
display: flex;
gap: 20px;
align-items: center;
}
button {
padding: 10px 20px;
background: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background: #45a049;
}
input[type="range"] {
width: 150px;
}
label {
display: flex;
flex-direction: column;
align-items: center;
gap: 5px;
}
</style>
</head>
<body>
<h1>Ball in Rotating Hexagon Simulation</h1>
<canvas id="canvas" width="800" height="600"></canvas>
<div class="controls">
<button onclick="resetSimulation()">Reset</button>
<button onclick="togglePause()"id="pauseBtn">Pause</button>
<label>
Rotation Speed
<input type="range" id="rotationSpeed" min="0" max="5" step="0.1" value="1">
<span id="rotationValue">1.0</span>
</label>
<label>
Gravity
<input type="range" id="gravity" min="0" max="1000" step="10" value="300">
<span id="gravityValue">300</span>
</label>
<label>
Ball Size
<input type="range" id="ballSize" min="3" max="15" step="1" value="8">
<span id="ballSizeValue">8</span>
</label>
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Simulation state
let isPaused = false;
let animationId;
// Hexagon properties
const hexagon = {
centerX: canvas.width / 2,
centerY: canvas.height / 2,
radius: 200,
rotation: 0,
rotationSpeed: 1
};
// Ball properties
let ball = {
x: hexagon.centerX,
y: hexagon.centerY,
vx: 50,
vy: 0,
radius: 8,
gravity: 300,
trail: []
};
// Get hexagon vertices
function getHexagonVertices() {
const vertices = [];
for (let i = 0; i < 6; i++) {
const angle = (i * Math.PI / 3) + hexagon.rotation;
vertices.push({
x: hexagon.centerX + hexagon.radius * Math.cos(angle),
y: hexagon.centerY + hexagon.radius * Math.sin(angle)
});
}
return vertices;
}
// Get hexagon edges (lines between vertices)
function getHexagonEdges() {
const vertices = getHexagonVertices();
const edges = [];
for (let i = 0; i < 6; i++) {
const start = vertices[i];
const end = vertices[(i + 1) % 6];
edges.push({ start, end });
}
return edges;
}
// Check collision with line segment
function checkLineCollision(ballX, ballY, ballRadius, lineStart, lineEnd) {
// Vector from line start to ball
const dx = ballX - lineStart.x;
const dy = ballY - lineStart.y;
// Vector of the line
const lineX = lineEnd.x - lineStart.x;
const lineY = lineEnd.y - lineStart.y;
// Length squared of the line
const lineLengthSq = lineX * lineX + lineY * lineY;
if (lineLengthSq === 0) return null;
// Project ball position onto line
const t = Math.max(0, Math.min(1, (dx * lineX + dy * lineY) / lineLengthSq));
// Closest point on line to ball
const closestX = lineStart.x + t * lineX;
const closestY = lineStart.y + t * lineY;
// Distance from ball to closest point
const distX = ballX - closestX;
const distY = ballY - closestY;
const distance = Math.sqrt(distX * distX + distY * distY);
if (distance <= ballRadius) {
// Normal vector (pointing away from line)
const normalX = distX / distance;
const normalY = distY / distance;
return {
normalX,
normalY,
penetration: ballRadius - distance,
contactX: closestX,
contactY: closestY
};
}
return null;
}
// Handle collision response
function handleCollision(collision) {
// Move ball out of collision
ball.x += collision.normalX * collision.penetration;
ball.y += collision.normalY * collision.penetration;
// Reflect velocity (perfectly elastic collision)
const dotProduct = ball.vx * collision.normalX + ball.vy * collision.normalY;
ball.vx -= 2 * dotProduct * collision.normalX;
ball.vy -= 2 * dotProduct * collision.normalY;
}
// Update simulation
function update(deltaTime) {
if (isPaused) return;
const dt = deltaTime / 1000; // Convert to seconds
// Update hexagon rotation
hexagon.rotation += hexagon.rotationSpeed * dt;
// Apply gravity
ball.vy += ball.gravity * dt;
// Update ball position
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
// Check collisions with hexagon edges
const edges = getHexagonEdges();
for (const edge of edges) {
const collision = checkLineCollision(ball.x, ball.y, ball.radius, edge.start, edge.end);
if (collision) {
handleCollision(collision);
}
}
// Add to trail
ball.trail.push({ x: ball.x, y: ball.y });
if (ball.trail.length > 100) {
ball.trail.shift();
}
}
// Render everything
function render() {
// Clear canvas
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw hexagon
const vertices = getHexagonVertices();
ctx.strokeStyle = '#00ff00';
ctx.lineWidth = 3;
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.stroke();
// Draw ball trail
if (ball.trail.length > 1) {
ctx.strokeStyle = '#ff6600';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(ball.trail[0].x, ball.trail[0].y);
for (let i = 1; i < ball.trail.length; i++) {
const alpha = i / ball.trail.length;
ctx.globalAlpha = alpha * 0.5;
ctx.lineTo(ball.trail[i].x, ball.trail[i].y);
}
ctx.stroke();
ctx.globalAlpha = 1;
}
// Draw ball
ctx.fillStyle = '#ff0000';
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fill();
// Draw center point
ctx.fillStyle = '#ffffff';
ctx.beginPath();
ctx.arc(hexagon.centerX, hexagon.centerY, 3, 0, Math.PI * 2);
ctx.fill();
}
// Animation loop
let lastTime = 0;
function animate(currentTime) {
const deltaTime = currentTime - lastTime;
lastTime = currentTime;
update(deltaTime);
render();
animationId = requestAnimationFrame(animate);
}
// Control functions
function resetSimulation() {
ball.x = hexagon.centerX;
ball.y = hexagon.centerY;
ball.vx = 50;
ball.vy = 0;
ball.trail = [];
hexagon.rotation = 0;
}
function togglePause() {
isPaused = !isPaused;
document.getElementById('pauseBtn').textContent = isPaused ? 'Resume' : 'Pause';
}
// Control event listeners
document.getElementById('rotationSpeed').addEventListener('input', (e) => {
hexagon.rotationSpeed = parseFloat(e.target.value);
document.getElementById('rotationValue').textContent = e.target.value;
});
document.getElementById('gravity').addEventListener('input', (e) => {
ball.gravity = parseFloat(e.target.value);
document.getElementById('gravityValue').textContent = e.target.value;
});
document.getElementById('ballSize').addEventListener('input', (e) => {
ball.radius = parseFloat(e.target.value);
document.getElementById('ballSizeValue').textContent = e.target.value;
});
// Start animation
animate(0);
</script>
</body>
</html>
The physics calculations handle proper collision detection with line segments, reflection of velocity vectors for elastic collisions, and realistic gravity effects. The ball will bounce around inside the rotating hexagon indefinitely due to the perfectly elastic collisions.