Make bullet physics simulation in 2D using HTML + JS (one file), use simple shapes
- User
Make bullet physics simulation in 2D using HTML + JS (one file), use simple shapes
- Assistant
Make bullet physics simulation in 2D using HTML + JS (one file), use simple shapes
Creating a 2D physics simulation using the Bullet Physics engine in a single HTML file can be achieved using Ammo.js, which is a JavaScript port of Bullet. Although Bullet is primarily a 3D physics engine, we can constrain it to 2D by fixing one of the axes (typically the Z-axis) to simulate 2D behavior.
Below is a complete HTML file that sets up a simple 2D physics simulation with basic shapes like boxes and circles. This example uses <canvas> for rendering and Ammo.js for the physics simulation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2D Physics Simulation with Ammo.js</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; background: #f0f0f0; }
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<!-- Include Ammo.js via CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/ammo.js/0.0.10/ammo.js"></script>
<script>
// Wait for Ammo.js to load
Ammo().then(function(Ammo) {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Physics variables
let physicsWorld;
const rigidBodies = [];
const tmpTransformation = new Ammo.btTransform();
// Initialize Ammo Physics
function initPhysics() {
const collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
const dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
const broadphase = new Ammo.btDbvtBroadphase();
const solver = new Ammo.btSequentialImpulseConstraintSolver();
physicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
physicsWorld.setGravity(new Ammo.btVector3(0, -9.81, 0));
}
// Create Ground
function createGround() {
const groundSize = { width: 50, height: 1 };
const groundPos = { x: 0, y: -5 };
// Collision shape
const shape = new Ammo.btBoxShape(new Ammo.btVector3(groundSize.width / 2, groundSize.height / 2, 1));
shape.setMargin(0.05);
// Transform
const transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin(new Ammo.btVector3(groundPos.x, groundPos.y, 0));
transform.setRotation(new Ammo.btQuaternion(0, 0, 0, 1));
// Mass and inertia
const mass = 0;
const localInertia = new Ammo.btVector3(0, 0, 0);
// Motion state
const motionState = new Ammo.btDefaultMotionState(transform);
// Rigid body
const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia);
const body = new Ammo.btRigidBody(rbInfo);
// Add to physics world
physicsWorld.addRigidBody(body);
}
// Create Box
function createBox(x, y, width, height, mass = 1) {
const shape = new Ammo.btBoxShape(new Ammo.btVector3(width / 2, height / 2, 1));
shape.setMargin(0.05);
const transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin(new Ammo.btVector3(x, y, 0));
transform.setRotation(new Ammo.btQuaternion(0, 0, 0, 1));
const localInertia = new Ammo.btVector3(0, 0, 0);
shape.calculateLocalInertia(mass, localInertia);
const motionState = new Ammo.btDefaultMotionState(transform);
const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia);
const body = new Ammo.btRigidBody(rbInfo);
physicsWorld.addRigidBody(body);
rigidBodies.push(body);
}
// Create Circle (approximated as a sphere in 2D)
function createCircle(x, y, radius, mass = 1) {
const shape = new Ammo.btSphereShape(radius);
shape.setMargin(0.05);
const transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin(new Ammo.btVector3(x, y, 0));
transform.setRotation(new Ammo.btQuaternion(0, 0, 0, 1));
const localInertia = new Ammo.btVector3(0, 0, 0);
shape.calculateLocalInertia(mass, localInertia);
const motionState = new Ammo.btDefaultMotionState(transform);
const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia);
const body = new Ammo.btRigidBody(rbInfo);
physicsWorld.addRigidBody(body);
rigidBodies.push(body);
}
// Initialize the scene
function init() {
initPhysics();
createGround();
// Create some boxes
for (let i = 0; i < 5; i++) {
createBox(Math.random() * 10 - 5, Math.random() * 10, 1, 1);
}
// Create some circles
for (let i = 0; i < 5; i++) {
createCircle(Math.random() * 10 - 5, Math.random() * 10 + 5, 0.5);
}
// Start the render loop
animate();
}
// Update physics
function updatePhysics(deltaTime) {
physicsWorld.stepSimulation(deltaTime, 10);
// Update rigid bodies
for (let i = 0; i < rigidBodies.length; i++) {
const body = rigidBodies[i];
const motionState = body.getMotionState();
if (motionState) {
motionState.getWorldTransform(tmpTransformation);
const p = tmpTransformation.getOrigin();
const q = tmpTransformation.getRotation();
body.position = { x: p.x(), y: p.y(), z: p.z() };
body.rotation = { x: q.x(), y: q.y(), z: q.z(), w: q.w() };
}
}
}
// Render the scene
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
// Transform for center and scaling
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.scale(20, -20); // 20 pixels per unit, flip Y-axis
// Draw ground
drawBox(0, -5, 50, 1, 'brown');
// Draw rigid bodies
for (let i = 0; i < rigidBodies.length; i++) {
const body = rigidBodies[i];
const pos = body.position;
const rot = body.rotation;
// Since we're simulating 2D, we ignore the z-axis rotation
const angle = 0; // Or compute based on rotation if needed
// Determine shape type
const shape = body.getCollisionShape();
const shapeType = shape.getShapeType();
if (shapeType === 'BOX_SHAPE_PROXYTYPE') {
const halfExtents = shape.getHalfExtentsWithMargin();
drawBox(pos.x, pos.y, halfExtents.x() * 2, halfExtents.y() * 2, 'blue', angle);
} else if (shapeType === 'SPHERE_SHAPE_PROXYTYPE') {
const radius = shape.getRadius();
drawCircle(pos.x, pos.y, radius, 'red');
}
}
ctx.restore();
}
// Drawing functions
function drawBox(x, y, width, height, color, angle = 0) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
ctx.fillStyle = color;
ctx.fillRect(-width / 2, -height / 2, width, height);
ctx.restore();
}
function drawCircle(x, y, radius, color) {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
let lastTime = null;
// Animation loop
function animate(time) {
requestAnimationFrame(animate);
if (lastTime === null) {
lastTime = time;
}
const deltaTime = (time - lastTime) / 1000;
lastTime = time;
updatePhysics(deltaTime);
render();
}
// Handle window resize
window.addEventListener('resize', function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// Start the simulation
init();
});
</script>
</body>
</html>
Including Ammo.js:
Canvas Setup:
<canvas> element is used for rendering the simulation visually.Initializing the Physics World:
physicsWorld) is created using Ammo.js, setting up the collision configuration, dispatcher, broadphase, and solver.Creating the Ground:
Creating Dynamic Bodies (Boxes and Circles):
btBoxShape with specified width and height.btSphereShape.Physics Simulation Loop:
animate function is called repeatedly using requestAnimationFrame.updatePhysics steps the simulation forward by the elapsed time.Rendering:
drawBox and drawCircle) handle the visual representation of the physics bodies.Handling Resizing:
2D Simulation with 3D Physics Engine:
Performance Considerations:
Further Enhancements:
If you're open to using a dedicated 2D physics engine, Matter.js is an excellent choice that's simpler to implement for 2D simulations. Here's a quick example using Matter.js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Matter.js 2D Physics Simulation</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; background: #f0f0f0; }
</style>
</head>
<body>
<!-- Include Matter.js via CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<script>
const { Engine, Render, Runner, Bodies, World } = Matter;
// Create engine
const engine = Engine.create();
const world = engine.world;
// Create renderer
const render = Render.create({
element: document.body,
engine: engine,
options: {
width: window.innerWidth,
height: window.innerHeight,
wireframes: false,
background: '#f0f0f0',
}
});
Render.run(render);
// Create runner
const runner = Runner.create();
Runner.run(runner, engine);
// Add ground
const ground = Bodies.rectangle(400, 600, 810, 60, { isStatic: true, render: { fillStyle: 'brown' } });
World.add(world, ground);
// Add boxes and circles
for (let i = 0; i < 5; i++) {
const box = Bodies.rectangle(200 + i * 60, 100, 50, 50, { restitution: 0.5, render: { fillStyle: 'blue' } });
World.add(world, box);
}
for (let i = 0; i < 5; i++) {
const circle = Bodies.circle(500 + i * 60, 100, 25, { restitution: 0.5, render: { fillStyle: 'red' } });
World.add(world, circle);
}
// Handle window resize
window.addEventListener('resize', function() {
render.canvas.width = window.innerWidth;
render.canvas.height = window.innerHeight;
Matter.Body.setPosition(ground, { x: window.innerWidth / 2, y: window.innerHeight - 30 });
Matter.Body.setVertices(ground, [
{ x: 0, y: window.innerHeight },
{ x: window.innerWidth, y: window.innerHeight },
{ x: window.innerWidth, y: window.innerHeight - 60 },
{ x: 0, y: window.innerHeight - 60 }
]);
});
</script>
</body>
</html>
This example leverages the simplicity and efficiency of Matter.js for 2D simulations and might be more suitable depending on your project requirements.
Not yet included in a published release.