In this blog post, we’ll explore how to create a simple interactive animation using JavaScript that detects collisions between two circles. This can be a fun project to learn about basic game development concepts like collision detection.

Setting Up the Canvas

We start by creating a canvas element in HTML where we’ll draw our circles. The canvas is set to a size of 1080×1080 pixels and styled to take up the entire viewport. We also create a div element to display the collision status text, positioned at the top left corner of the canvas.

Defining the Circles

We define two circle objects using JavaScript. The first circle (circle1) is randomly positioned within the canvas and has a fixed radius of 60 pixels. The second circle (circle2) is initially placed at the center of the canvas and will follow the mouse cursor’s position.

Mouse Movement Event

We add an event listener to the canvas to track the movement of the mouse. When the mouse moves, the position of circle2 is updated to match the mouse cursor’s coordinates relative to the canvas.

Detecting Collisions

To detect collisions between the two circles, we calculate the distance between their centers using the distance formula. If the distance is less than the sum of the radii of the two circles, they are considered to be colliding.

Drawing the Circles

In the draw function, we clear the canvas and redraw both circles at their current positions. The color of the circles is set to green initially but changes to red if a collision is detected. We also update the collision status text to display “true” or “false” depending on whether a collision is detected.

Animation Loop

The draw function is called recursively using requestAnimationFrame, which creates a smooth animation effect. The circles are redrawn and the collision status is updated in each frame of the animation.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            margin: 0;
            overflow: hidden;
        }
        canvas{
            display: block;
        }
        #collisionText{
            position: absolute;
            top:10px;
            left: 10px;
            font-size: 18px;
            
        }
        
    </style>
</head>
<body>
    <canvas id="canvas" width="1080" height="1080">
        
    </canvas>
    <div id="collisionText"></div>
    <script src="script.js"></script>
</body>
</html>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const collisionText = document.getElementById('collisionText');
const circle1 = {
    x: Math.random()*canvas.width,
    y: Math.random()*canvas.height,
    radius:60,
    color:'green'
};

const circle2= {
    x: canvas.width/2,
    y:canvas.height/2,
    radius:60,
    color:'green'
};

canvas.addEventListener('mousemove',function(event){
    circle2.x = event.clientX-canvas.getBoundingClientRect().left;
    circle2.y = event.clientY-canvas.getBoundingClientRect().top;

})

function detectCollision(){
    const dx = circle1.x - circle2.x;
    const dy = circle1.y - circle2.y;
    const distance = Math.sqrt(dx*dx+ dy*dy);
    return distance<circle1.radius+circle2.radius;
}

function draw(){
    ctx.clearRect(0,0,canvas.width,canvas.height);

    //Draw circle 1
    ctx.beginPath();
    ctx.arc(circle1.x,circle1.y,circle1.radius,0,Math.PI*2);
    ctx.fillStyle = circle1.color;
    ctx.fill();
    ctx.closePath();

    //Draw circle 2
    ctx.beginPath();
    ctx.arc(circle2.x,circle2.y,circle2.radius,0,Math.PI*2);
    ctx.fillStyle = circle2.color;
    ctx.fill();
    ctx.closePath();

    //check for collision
    const isColliding = detectCollision();
    collisionText.innerText= isColliding?'true':'false';

    //change the color base on collision
    circle1.color= isColliding?'red':'green';
    circle2.color= isColliding?'red':'green';
    requestAnimationFrame(draw);

}
draw()