Make 2D physic engine using HTML + JS (one file) Implement: 1. Advanced physics 2.…
- User
Make 2D physic engine using HTML + JS (one file)
Implement:
- Advanced physics
- Viewport
- Shapes
- Pretty UI
- Assistant
Make 2D physic engine using HTML + JS (one file)
Implement:
Sure! Below is a single HTML file that implements a 2D physics engine using HTML and JavaScript. This engine includes advanced physics with collision detection and response, a viewport that allows panning and zooming, various shapes (circles and rectangles), and a simple but pretty UI for interaction.
You can copy the entire code below and save it as an .html file, then open it in a web browser to see it in action.
<!DOCTYPE html>
<html>
<head>
<title>2D Physics Engine</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #222;
}
canvas {
display: block;
}
#ui {
position: absolute;
top: 10px;
left: 10px;
color: white;
font-family: Arial, sans-serif;
z-index: 10;
user-select: none;
}
#ui button, #ui input {
margin-right: 5px;
padding: 5px 10px;
background-color: #444;
border: none;
color: white;
cursor: pointer;
font-size: 14px;
}
#ui button:hover {
background-color: #555;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="ui">
<button id="addCircle">Add Circle</button>
<button id="addRectangle">Add Rectangle</button>
<button id="reset">Reset</button>
</div>
<script>
// Get the canvas and context
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Fullscreen canvas setup
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Viewport variables for panning and zooming
let scale = 1;
let offsetX = 0;
let offsetY = 0;
let isDragging = false;
let dragStart = { x: 0, y: 0 };
// Event listeners for viewport interaction
canvas.addEventListener('mousedown', function(e) {
isDragging = true;
dragStart.x = e.clientX - offsetX;
dragStart.y = e.clientY - offsetY;
});
canvas.addEventListener('mouseup', function(e) {
isDragging = false;
});
canvas.addEventListener('mousemove', function(e) {
if (isDragging) {
offsetX = e.clientX - dragStart.x;
offsetY = e.clientY - dragStart.y;
}
});
canvas.addEventListener('wheel', function(e) {
e.preventDefault();
let zoomAmount = e.deltaY * -0.001;
scale += zoomAmount;
scale = Math.max(scale, 0.1);
});
// Vector2D class for vector operations
class Vector2D {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(v) { return new Vector2D(this.x + v.x, this.y + v.y); }
subtract(v) { return new Vector2D(this.x - v.x, this.y - v.y); }
multiply(scalar) { return new Vector2D(this.x * scalar, this.y * scalar); }
dot(v) { return this.x * v.x + this.y * v.y; }
length() { return Math.sqrt(this.x * this.x + this.y * this.y); }
normalize() {
let len = this.length();
return new Vector2D(this.x / len, this.y / len);
}
}
// Base Body class for physics bodies
class Body {
constructor(x, y, mass, velX = 0, velY = 0) {
this.position = new Vector2D(x, y);
this.velocity = new Vector2D(velX, velY);
this.mass = mass;
this.invMass = mass > 0 ? 1 / mass : 0;
this.acceleration = new Vector2D(0, 0);
this.restitution = 0.8; // Coefficient of restitution
}
applyForce(force) {
// F = m * a => a = F / m
let a = force.multiply(this.invMass);
this.acceleration = this.acceleration.add(a);
}
update(dt) {
this.velocity = this.velocity.add(this.acceleration.multiply(dt));
this.position = this.position.add(this.velocity.multiply(dt));
this.acceleration = new Vector2D(0, 0); // Reset acceleration
}
draw(ctx) {
// To be overridden by subclasses
}
}
// Circle class extending from Body
class Circle extends Body {
constructor(x, y, radius, mass, velX = 0, velY = 0) {
super(x, y, mass, velX, velY);
this.radius = radius;
this.color = `hsl(${Math.random() * 360}, 70%, 50%)`;
}
draw(ctx) {
ctx.beginPath();
ctx.arc(
(this.position.x + offsetX) * scale,
(this.position.y + offsetY) * scale,
this.radius * scale,
0,
2 * Math.PI
);
ctx.fillStyle = this.color;
ctx.fill();
}
}
// Rectangle class extending from Body
class Rectangle extends Body {
constructor(x, y, width, height, mass, velX = 0, velY = 0) {
super(x, y, mass, velX, velY);
this.width = width;
this.height = height;
this.color = `hsl(${Math.random() * 360}, 70%, 50%)`;
}
draw(ctx) {
ctx.fillStyle = this.color;
ctx.fillRect(
(this.position.x - this.width / 2 + offsetX) * scale,
(this.position.y - this.height / 2 + offsetY) * scale,
this.width * scale,
this.height * scale
);
}
}
// Array to hold all bodies in the simulation
let bodies = [];
// Physics update function
function update(dt) {
// Apply gravity to all bodies
bodies.forEach(body => {
if (body.mass > 0) {
body.applyForce(new Vector2D(0, 9.8 * body.mass)); // Gravity force
}
});
// Update positions of all bodies
bodies.forEach(body => {
body.update(dt);
});
// Check and resolve collisions
for (let i = 0; i < bodies.length; i++) {
for (let j = i + 1; j < bodies.length; j++) {
let bodyA = bodies[i];
let bodyB = bodies[j];
if (bodyA instanceof Circle && bodyB instanceof Circle) {
resolveCircleCircleCollision(bodyA, bodyB);
}
// Add more collision cases here if needed
}
}
}
// Collision resolution between two circles
function resolveCircleCircleCollision(circleA, circleB) {
let normal = circleB.position.subtract(circleA.position);
let dist = normal.length();
let combinedRadii = circleA.radius + circleB.radius;
if (dist < combinedRadii) {
// Circles are colliding
let penetrationDepth = combinedRadii - dist;
let collisionNormal = normal.normalize();
// Push circles apart
let totalInverseMass = circleA.invMass + circleB.invMass;
if (totalInverseMass == 0) return; // Both have infinite mass
let correction = collisionNormal.multiply(penetrationDepth / totalInverseMass);
circleA.position = circleA.position.subtract(correction.multiply(circleA.invMass));
circleB.position = circleB.position.add(correction.multiply(circleB.invMass));
// Compute relative velocity
let relativeVelocity = circleB.velocity.subtract(circleA.velocity);
let velocityAlongNormal = relativeVelocity.dot(collisionNormal);
if (velocityAlongNormal > 0) return; // They are moving apart
// Compute restitution
let e = Math.min(circleA.restitution, circleB.restitution);
// Compute impulse scalar
let j = -(1 + e) * velocityAlongNormal;
j /= totalInverseMass;
// Apply impulse
let impulse = collisionNormal.multiply(j);
circleA.velocity = circleA.velocity.subtract(impulse.multiply(circleA.invMass));
circleB.velocity = circleB.velocity.add(impulse.multiply(circleB.invMass));
}
}
// Render function to draw all bodies
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
bodies.forEach(body => {
body.draw(ctx);
});
}
// Main animation loop
let lastTime = 0;
function loop(timestamp) {
let dt = (timestamp - lastTime) / 1000; // Convert ms to s
dt = Math.min(dt, 0.02); // Max dt to prevent spiral of death
lastTime = timestamp;
update(dt);
render();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
// UI buttons event listeners
document.getElementById('addCircle').addEventListener('click', () => {
let radius = 20 + Math.random() * 20;
let mass = radius; // Mass proportional to size
let x = (Math.random() * canvas.width - offsetX * scale) / scale;
let y = (-canvas.height / 2 - offsetY * scale) / scale;
let circle = new Circle(x, y, radius, mass);
bodies.push(circle);
});
document.getElementById('addRectangle').addEventListener('click', () => {
let width = 40 + Math.random() * 40;
let height = 40 + Math.random() * 40;
let mass = (width + height) / 2; // Mass proportional to size
let x = (Math.random() * canvas.width - offsetX * scale) / scale;
let y = (-canvas.height / 2 - offsetY * scale) / scale;
let rectangle = new Rectangle(x, y, width, height, mass);
bodies.push(rectangle);
});
document.getElementById('reset').addEventListener('click', () => {
bodies = [];
});
</script>
</body>
</html>
Advanced Physics: The physics engine includes gravity, basic collision detection, and collision response with restitution (bounciness). It currently handles collisions between circles but can be extended to handle other shapes.
Viewport: You can pan the viewport by clicking and dragging the mouse. Zoom in and out using the mouse wheel. This allows you to explore different parts of the simulation space.
Shapes: The engine supports dynamic circles and rectangles. You can add them to the simulation using the UI buttons. Each shape is assigned a random color.
Pretty UI: A simple and clean UI is provided with buttons to add circles, add rectangles, and reset the simulation. The UI is styled to blend well with the simulation canvas.
Add Circle: Click this button to add a new circle to the simulation. Circles have random sizes and are placed at a random horizontal position at the top of the viewport.
Add Rectangle: Click this button to add a new rectangle. Rectangles also have random sizes and initial positions.
Reset: Clears all bodies from the simulation, allowing you to start fresh.
Pan: Click and drag anywhere on the canvas to pan the viewport.
Zoom: Use the mouse wheel to zoom in and out, adjusting the scale of the viewport.
Collision Detection: Currently, only circle-circle collisions are implemented. Detecting and resolving collisions between rectangles and between circles and rectangles require more complex algorithms like the Separating Axis Theorem (SAT).
Performance: The simulation is simple and may not perform well with a very large number of bodies due to the O(n²) collision detection loop. Optimization techniques can be applied for better performance.
Extensibility: This engine is a basic framework that can be extended with more advanced physics features, shapes, and optimizations.
Enjoy experimenting with the 2D physics engine!
Not yet included in a published release.