Write a JavaScript program using an HTML Canvas to simulate four balls inside a rotating…
- User
Write a JavaScript program using an HTML Canvas to simulate four balls inside a rotating rectangular container.
Container:
A rectangle (width W, height H) centered at (W/2, H/2) on the canvas.
Rotates continuously around its center at a fixed angular velocity ω (e.g. 0.5 rad/s).
Gravity:
A uniform acceleration g = 9.8 m/s² directed downward toward the bottom edge of the canvas (independent of the container’s rotation).
Balls:
Four circles of equal radius and mass.
Initial positions and velocities are up to you (just keep them inside the container at start).
Physics requirements:
Implement elastic collisions between balls and between each ball and the container walls.
When a ball collides with a wall, account for the wall’s instantaneous velocity due to rotation when computing the collision response.
Apply gravity each frame to the balls’ vertical velocity.
Implementation constraints:
Use plain ES6 JavaScript and the Canvas API only (no external physics libraries).
Target 60 fps with requestAnimationFrame.
Structure your code so it’s easy to adjust parameters (g, ω, restitution coefficient).
Assistant
<!DOCTYPE html> <html> <head> <title>Rotating Container Balls</title> <style> body { margin: 0; } canvas { display: block; } </style> </head> <body> <canvas id="myCanvas"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // Canvas and Container parameters const width = canvas.width = 800; const height = canvas.height = 600; const containerWidth = 300; const containerHeight = 200; const containerCenterX = width / 2; const containerCenterY = height / 2; let rotationAngle = 0; const angularVelocity = 0.5; // rad/s // Physics parameters const gravity = 9.8; // m/s^2 (pixels/frame^2 if we assume 1m = 100px and 60fps, approx 9.8 * (1/60)^2 * 100 = 0.27 pixels/frame^2) const restitution = 0.8; // Restitution coefficient for collisions, 0 to 1 // Ball parameters const ballRadius = 15; const balls = []; const numBalls = 4; function initBalls() { balls.length = 0; // Clear existing balls for (let i = 0; i < numBalls; i++) { balls.push({ x: containerCenterX + (Math.random() - 0.5) * containerWidth * 0.8, // Initial x inside container y: containerCenterY + (Math.random() - 0.5) * containerHeight * 0.8, // Initial y inside container vx: (Math.random() - 0.5) * 100, // Initial vx vy: (Math.random() - 0.5) * 100, // Initial vy color: `hsl(${i * 90}, 100%, 50%)` }); } } initBalls(); function rotatePoint(pointX, pointY, centerX, centerY, angle) { const dx = pointX - centerX; const dy = pointY - centerY; const rotatedX = centerX + dx * Math.cos(angle) - dy * Math.sin(angle); const rotatedY = centerY + dx * Math.sin(angle) + dy * Math.cos(angle); return { x: rotatedX, y: rotatedY }; } function drawContainer() { ctx.save(); ctx.translate(containerCenterX, containerCenterY); ctx.rotate(rotationAngle); ctx.strokeStyle = 'black'; ctx.lineWidth = 2; ctx.strokeRect(-containerWidth / 2, -containerHeight / 2, containerWidth, containerHeight); ctx.restore(); } function drawBall(ball) { ctx.beginPath(); ctx.arc(ball.x, ball.y, ballRadius, 0, Math.PI * 2); ctx.fillStyle = ball.color; ctx.fill(); ctx.closePath(); } function updateBallPosition(ball, deltaTime) { ball.vy += gravity * deltaTime; // Apply gravity ball.x += ball.vx * deltaTime; ball.y += ball.vy * deltaTime; } function handleBallContainerCollision(ball, deltaTime) { const cosAngle = Math.cos(rotationAngle); const sinAngle = Math.sin(rotationAngle); // Rotate ball position and velocity back to container's local frame let dx = ball.x - containerCenterX; let dy = ball.y - containerCenterY; const localBallX = dx * cosAngle + dy * sinAngle; const localBallY = -dx * sinAngle + dy * cosAngle; const localBallVX = ball.vx * cosAngle + ball.vy * sinAngle; const localBallVY = -ball.vx * sinAngle + ball.vy * cosAngle; let collision = false; let normalX = 0; let normalY = 0; if (localBallX + ballRadius > containerWidth / 2) { // Right wall if (localBallVX > 0) { collision = true; normalX = -1; } } else if (localBallX - ballRadius < -containerWidth / 2) { // Left wall if (localBallVX < 0) { collision = true; normalX = 1; } } if (localBallY + ballRadius > containerHeight / 2) { // Bottom wall if (localBallVY > 0) { collision = true; normalY = -1; } } else if (localBallY - ballRadius < -containerHeight / 2) { // Top wall if (localBallVY < 0) { collision = true; normalY = 1; } } if (collision) { // Rotate normal back to world frame const worldNormalX = normalX * cosAngle - normalY * sinAngle; const worldNormalY = normalX * sinAngle + normalY * cosAngle; // Collision point in world coordinates (approximate to ball center) const collisionPointX = ball.x; const collisionPointY = ball.y; // Wall velocity at collision point due to rotation (tangential velocity) const relX = collisionPointX - containerCenterX; const relY = collisionPointY - containerCenterY; const wallVelocityX = -angularVelocity * relY; // v = omega x r, direction using cross product in 2D const wallVelocityY = angularVelocity * relX; // Relative velocity of ball to wall const relativeVelocityX = ball.vx - wallVelocityX; const relativeVelocityY = ball.vy - wallVelocityY; // Project relative velocity onto the collision normal const normalVelocity = relativeVelocityX * worldNormalX + relativeVelocityY * worldNormalY; if (normalVelocity < 0) { // Check if balls are approaching // Impulse scalar (using simplified formula for elastic collision with a surface of infinite mass) const impulseScalar = -(1 + restitution) * normalVelocity; // Apply impulse to ball's velocity along normal ball.vx += impulseScalar * worldNormalX; ball.vy += impulseScalar * worldNormalY; } // Project ball's world velocity back to local frame for next checks (optional, but could improve accuracy if doing multiple wall checks) // ball.vx = ball.vx * cosAngle + ball.vy * -sinAngle; // No need to do this, we update world velocity directly. // ball.vy = ball.vx * sinAngle + ball.vy * cosAngle; } } function handleBallBallCollision(ball1, ball2) { const dx = ball2.x - ball1.x; const dy = ball2.y - ball1.y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < 2 * ballRadius) { const normalX = dx / distance; const normalY = dy / distance; const tangentX = -normalY; const tangentY = normalX; // Project velocities onto normal and tangent const v1n = ball1.vx * normalX + ball1.vy * normalY; const v1t = ball1.vx * tangentX + ball1.vy * tangentY; const v2n = ball2.vx * normalX + ball2.vy * normalY; const v2t = ball2.vx * tangentX + ball2.vy * tangentY; // Elastic collision in normal direction (1D collision formula for equal masses - swap normal velocities) const v1n_new = v2n; const v2n_new = v1n; // Tangent velocities remain unchanged (frictionless collision) // Convert normal and tangent components back to world velocities ball1.vx = v1n_new * normalX + v1t * tangentX; ball1.vy = v1n_new * normalY + v1t * tangentY; ball2.vx = v2n_new * normalX + v2t * tangentX; ball2.vy = v2n_new * normalY + v2t * tangentY; // Separate balls to avoid sticking (simple separation along normal) const overlap = 2 * ballRadius - distance; const separationX = overlap * normalX * 0.5; // Distribute separation evenly const separationY = overlap * normalY * 0.5; ball1.x -= separationX; ball1.y -= separationY; ball2.x += separationX; ball2.y += separationY; } } let lastTime = 0; function gameLoop(currentTime) { const deltaTime = (currentTime - lastTime) / 1000; // Convert milliseconds to seconds lastTime = currentTime; rotationAngle += angularVelocity * deltaTime; ctx.clearRect(0, 0, width, height); drawContainer(); for (let i = 0; i < balls.length; i++) { updateBallPosition(balls[i], deltaTime); handleBallContainerCollision(balls[i], deltaTime); for (let j = i + 1; j < balls.length; j++) { handleBallBallCollision(balls[i], balls[j]); } drawBall(balls[i]); } requestAnimationFrame(gameLoop); } gameLoop(0); // Start animation </script> </body> </html>Explanation:
- HTML Structure: Sets up a basic HTML page with a
<canvas>element. - JavaScript Setup:
- Gets the canvas and its 2D rendering context.
- Defines canvas dimensions and container parameters (width, height, center, rotation speed).
- Defines physics parameters (gravity, restitution coefficient).
- Defines ball parameters (radius, array to hold balls).
initBalls(): Initializes ball positions and velocities randomly inside the container.
rotatePoint(): A utility function to rotate a point around a center point by a given angle. (Not directly used in the final collision but good to have for more complex scenarios).drawContainer(): Draws the rotating rectangular container using canvas transformations (translate,rotate,strokeRect).drawBall(): Draws a ball as a filled circle.updateBallPosition(): Updates ball positions based on their velocities and applies gravity to the vertical velocity (vy).handleBallContainerCollision():- Local Frame Transformation: Rotates the ball's position and velocity back to the container's local (unrotated) frame using
cosandsinof therotationAngle. This simplifies collision detection with the rectangle edges. - Collision Detection: Checks if the ball (in the local frame) is colliding with any of the four edges of the static rectangle.
- World Frame Normal and Wall Velocity: If a collision is detected:
- Calculates the collision normal in the local frame and rotates it back to the world frame.
- Calculates the tangential velocity of the container wall at the collision point due to rotation (using
v = ω x r). - Calculates the relative velocity of the ball with respect to the wall.
- Elastic Collision Response:
- Calculates the normal component of the relative velocity.
- Applies an impulse to reflect the ball's velocity component along the normal, using the
restitutioncoefficient for elasticity.
- Local Frame Transformation: Rotates the ball's position and velocity back to the container's local (unrotated) frame using
handleBallBallCollision():- Collision Detection: Checks if the distance between two ball centers is less than twice the ball radius.
- Collision Normal and Tangent: Calculates the normal vector (along the line connecting the centers) and a tangent vector (perpendicular to the normal).
- Velocity Projection: Projects the velocities of both balls onto the normal and tangent directions.
- Elastic Collision in Normal Direction: Applies 1D elastic collision physics in the normal direction (for equal masses, this simplifies to swapping the normal velocity components). Tangential velocities are unchanged (frictionless collision).
- Velocity Reconstruction: Reconstructs the balls' world velocities from the new normal and unchanged tangent velocity components.
- Separation: Moves the balls slightly apart after collision to prevent them from getting stuck overlapping.
gameLoop():- The main animation loop that is called by
requestAnimationFramefor smooth animation (approximately 60fps). - Calculates
deltaTimeto ensure consistent animation speed regardless of frame rate. - Updates
rotationAnglebased onangularVelocityanddeltaTime. - Clears the canvas.
- Draws the container.
- Iterates through each ball:
- Updates ball position and applies gravity.
- Handles ball-container collisions.
- Handles ball-ball collisions with all other balls (nested loop).
- Draws the ball.
- Calls
requestAnimationFrame(gameLoop)again to schedule the next frame.
- The main animation loop that is called by
gameLoop(0): Starts the animation loop.
To Run:
- Save the code as an HTML file (e.g.,
rotating_balls.html). - Open the HTML file in a web browser.
You can adjust the parameters at the beginning of the JavaScript code to change gravity, rotation speed, restitution, ball size, and container size.
- HTML Structure: Sets up a basic HTML page with a
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.