Calculator Tools Calculator Tools
Create

2D Collision Game

Nov 17, 2023

About this app

A simple 2D game where cubes collide and interact with a wall, tracking the number of collisions.

javascript function checkCollision(cube1, cube2) { return cube1.x < cube2.x + cube2.width && cube1.x + cube1.width > cube2.x && cube1.y < cube2.y + cube2.height && cube1.y + cube1.height > cube2.y; } function resolveCollision(cube1, cube2) { const velocityDiff = cube1.velocity - cube2.velocity; // Calculate the new velocities after the collision const newVelocity1 = (cube1.velocity * (cube1.mass - cube2.mass) + (2 * cube2.mass * cube2.velocity)) / (cube1.mass + cube2.mass); const newVelocity2 = (cube2.velocity * (cube2.mass - cube1.mass) + (2 * cube1.mass * cube1.velocity)) / (cube1.mass + cube2.mass); // Update the velocities of the cubes cube1.velocity = newVelocity1; cube2.velocity = newVelocity2; collisions++; updateCollisionInfo(); }

Related apps

Put this on your site

Source

                    javascript
function checkCollision(cube1, cube2) {
return cube1.x < cube2.x + cube2.width &&
cube1.x + cube1.width > cube2.x &&
cube1.y < cube2.y + cube2.height &&
cube1.y + cube1.height > cube2.y;
}

function resolveCollision(cube1, cube2) {
const velocityDiff = cube1.velocity - cube2.velocity;

// Calculate the new velocities after the collision
const newVelocity1 = (cube1.velocity * (cube1.mass - cube2.mass) + (2 * cube2.mass * cube2.velocity)) / (cube1.mass + cube2.mass);
const newVelocity2 = (cube2.velocity * (cube2.mass - cube1.mass) + (2 * cube1.mass * cube1.velocity)) / (cube1.mass + cube2.mass);

// Update the velocities of the cubes
cube1.velocity = newVelocity1;
cube2.velocity = newVelocity2;

collisions++;
updateCollisionInfo();
}