Using HTML + JS (one file) create a plush physic simulation of 2d ball, provide full code
- User
Using HTML + JS (one file) create a plush physic simulation of 2d ball, provide full code
- Assistant
Using HTML + JS (one file) create a plush physic simulation of 2d ball, provide full code
Sure! Below is a complete HTML file that includes a 2D physics simulation of a ball using HTML5 Canvas and JavaScript. This simulation features gravity, collision with the ground, and basic air resistance. You can open this code in any modern web browser to see the simulation in action.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2D Ball Physics Simulation</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #222;
}
canvas {
display: block;
background-color: #eee;
}
</style>
</head>
<body>
<canvas id="simulationCanvas"></canvas>
<script>
// Get the canvas and context
const canvas = document.getElementById('simulationCanvas');
const ctx = canvas.getContext('2d');
// Set canvas size
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// Ball object
class Ball {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.vx = 0; // Velocity X
this.vy = 0; // Velocity Y
this.ax = 0; // Acceleration X
this.ay = 0; // Acceleration Y
this.mass = 1;
this.bounceFactor = 0.7; // Energy lost on bounce
this.friction = 0.99; // Air resistance
}
applyForce(fx, fy) {
this.ax += fx / this.mass;
this.ay += fy / this.mass;
}
update(deltaTime) {
// Update velocity
this.vx += this.ax * deltaTime;
this.vy += this.ay * deltaTime;
// Apply air resistance
this.vx *= this.friction;
this.vy *= this.friction;
// Update position
this.x += this.vx * deltaTime;
this.y += this.vy * deltaTime;
// Reset acceleration
this.ax = 0;
this.ay = 0;
// Handle collisions with walls
// Left and Right
if (this.x - this.radius < 0) {
this.x = this.radius;
this.vx = -this.vx * this.bounceFactor;
} else if (this.x + this.radius > canvas.width) {
this.x = canvas.width - this.radius;
this.vx = -this.vx * this.bounceFactor;
}
// Top and Bottom
if (this.y - this.radius < 0) {
this.y = this.radius;
this.vy = -this.vy * this.bounceFactor;
} else if (this.y + this.radius > canvas.height) {
this.y = canvas.height - this.radius;
this.vy = -this.vy * this.bounceFactor;
// If velocity is very small, stop the ball to prevent endless bouncing
if (Math.abs(this.vy) < 0.1) {
this.vy = 0;
}
}
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
}
// Initialize the ball
const ball = new Ball(canvas.width / 2, canvas.height / 4, 30, '#3498db');
// Gravity constant
const gravity = 980; // pixels per second squared
// Time management
let lastTime = null;
// Animation loop
function animate(time) {
if (!lastTime) {
lastTime = time;
requestAnimationFrame(animate);
return;
}
const deltaTime = (time - lastTime) / 1000; // Convert to seconds
lastTime = time;
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Apply gravity
ball.applyForce(0, ball.mass * gravity);
// Update ball physics
ball.update(deltaTime);
// Draw the ball
ball.draw(ctx);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
// Optional: Add interactivity - click to apply an impulse
canvas.addEventListener('mousedown', function(event) {
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
// Calculate direction from ball to mouse
const dx = mouseX - ball.x;
const dy = mouseY - ball.y;
const distance = Math.sqrt(dx * dx + dy * dy);
const forceMagnitude = 50000; // Adjust for desired impulse
if (distance < 200) { // Apply only if within a certain distance
const fx = (dx / distance) * forceMagnitude;
const fy = (dy / distance) * forceMagnitude;
ball.applyForce(fx, fy);
}
});
</script>
</body>
</html>
Gravity: The ball is constantly pulled downwards by gravity. The gravity constant can be adjusted (gravity = 980 pixels/s²) to change the strength.
Collision Detection: The ball detects collisions with the canvas boundaries (walls, floor, and ceiling) and bounces off them. The bounceFactor determines how much energy is retained after each bounce (set to 0.7 by default).
Air Resistance: A simple friction model is applied to simulate air resistance, gradually slowing down the ball's movement.
Interactivity: You can click anywhere on the canvas to apply an impulse force to the ball, pushing it in the direction of the click. This allows you to interact with the simulation and give the ball a "kick."
Responsive Canvas: The canvas resizes automatically to fit the browser window.
Ball Class: Encapsulates the properties and behaviors of the ball, including position, velocity, acceleration, mass, and methods to apply forces, update physics, and draw itself on the canvas.
Animation Loop: Uses requestAnimationFrame to create a smooth animation loop. In each frame, it clears the canvas, applies gravity, updates the ball's physics, and redraws the ball.
Force Application: Gravity is applied every frame as a constant downward force. When the user clicks, an additional force is applied based on the mouse position relative to the ball.
Ball Properties: You can change the ball's radius, color, mass, bounce factor, and friction by modifying the Ball class instance.
Forces: Adjust the gravity and impulse force magnitudes to change how the ball behaves.
Interactivity: Extend the interactivity by adding more event listeners (e.g., for keyboard controls) or adding multiple balls for more complex simulations.
Feel free to modify the code to better fit your requirements or to add more features!
Not yet included in a published release.