<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>2D Physics Boxes Game</title>
<style>
/* Style the canvas */
canvas {
border: 1px solid black;
display: block;
margin: 0 auto;
background-color: #f0f0f0;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>2D Physics Boxes Game</h1>
<p>Click on the canvas to spawn boxes.</p>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
// Get the canvas and context
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
// Array to store all boxes
var boxes = [];
// Gravity acceleration (pixels per second squared)
var gravity = 800;
// Variable to store the time of the last frame
var lastTime = 0;
// Box constructor function
function Box(x, y, width, height) {
this.x = x; // X position
this.y = y; // Y position
this.width = width; // Width of the box
this.height = height; // Height of the box
this.vx = 0; // Velocity in X direction
this.vy = 0; // Velocity in Y direction
}
// Function to handle mouse clicks and spawn new boxes
canvas.addEventListener('mousedown', function(event) {
// Get mouse position relative to the canvas
var rect = canvas.getBoundingClientRect();
var mouseX = event.clientX - rect.left;
var mouseY = event.clientY - rect.top;
// Create a new box with random size between 20 and 50 pixels
var boxSize = 20 + Math.random() * 30;
var newBox = new Box(mouseX - boxSize / 2, mouseY - boxSize / 2, boxSize, boxSize);
// Add the new box to the array
boxes.push(newBox);
});
// Function to update the physics of the boxes
function update(deltaTime) {
// Iterate over all boxes
boxes.forEach(function(box) {
// Apply gravity to vertical velocity
box.vy += gravity * deltaTime;
// Update box position
box.x += box.vx * deltaTime;
box.y += box.vy * deltaTime;
// Collision detection with the floor
if (box.y + box.height > canvas.height) {
box.y = canvas.height - box.height;
box.vy *= -0.5; // Reverse and reduce vertical velocity
}
// Collision detection with walls
if (box.x < 0) {
box.x = 0;
box.vx *= -0.5; // Reverse and reduce horizontal velocity
} else if (box.x + box.width > canvas.width) {
box.x = canvas.width - box.width;
box.vx *= -0.5;
}
});
// Collision detection between boxes
for (var i = 0; i < boxes.length; i++) {
for (var j = i + 1; j < boxes.length; j++) {
var boxA = boxes[i];
var boxB = boxes[j];
if (isColliding(boxA, boxB)) {
// Simple collision response: swap velocities
var tempVx = boxA.vx;
var tempVy = boxA.vy;
boxA.vx = boxB.vx;
boxA.vy = boxB.vy;
boxB.vx = tempVx;
boxB.vy = tempVy;
// Adjust positions to prevent sticking
resolveCollision(boxA, boxB);
}
}
}
}
// Function to check if two boxes are colliding
function isColliding(boxA, boxB) {
return boxA.x < boxB.x + boxB.width &&
boxA.x + boxA.width > boxB.x &&
boxA.y < boxB.y + boxB.height &&
boxA.y + boxA.height > boxB.y;
}
// Function to adjust positions after collision to prevent boxes from sticking together
function resolveCollision(boxA, boxB) {
var overlapX = (boxA.x + boxA.width / 2) - (boxB.x + boxB.width / 2);
var overlapY = (boxA.y + boxA.height / 2) - (boxB.y + boxB.height / 2);
if (Math.abs(overlapX) > Math.abs(overlapY)) {
// Resolve X overlap
if (overlapX > 0) {
boxA.x += 1;
boxB.x -= 1;
} else {
boxA.x -= 1;
boxB.x += 1;
}
} else {
// Resolve Y overlap
if (overlapY > 0) {
boxA.y += 1;
boxB.y -= 1;
} else {
boxA.y -= 1;
boxB.y += 1;
}
}
}
// Function to draw the boxes on the canvas
function draw() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw each box
boxes.forEach(function(box) {
ctx.fillStyle = 'blue';
ctx.fillRect(box.x, box.y, box.width, box.height);
});
}
// The game loop function
function gameLoop(timestamp) {
// Calculate the time difference since the last frame
var deltaTime = (timestamp - lastTime) / 1000; // Convert milliseconds to seconds
lastTime = timestamp;
// Update the game state
update(deltaTime);
// Draw everything
draw();
// Request the next frame
requestAnimationFrame(gameLoop);
}
// Start the game loop
requestAnimationFrame(gameLoop);
</script>
</body>
</html>
This simple 2D game demonstrates how you can create an interactive physics simulation using only HTML and JavaScript in a single file. By clicking on the canvas, you can spawn boxes that fall under gravity and collide with each other and the boundaries of the canvas. This foundation can be built upon to create more complex games and simulations.