Creating a Balloon Pop game using Three.js

Creating a Balloon Pop game using Three.js

Using three.js, I have created this game ballon pop for learning purposes. This blog goes through the important steps of creating the game.
Game is hosted at balloonpop Please do visit and try clicking on balloons to pop them.

Lets get started Screen Shot 2020-12-31 at 8.48.19 PM.png

Creating Balloons in the Scene: SpehereGeometry can be used to create ballon. we can randomly generate balloon with random colors and random positions in X-Z plane with Y being fixed negative values. so the createSphere() will keep on adding spheres in the scene.

let createGeometry = function() {
        let material = new THREE.MeshPhongMaterial({
            color: Math.random() * 0Xaf62ff,
            shininess: 10,
            side: THREE.DoubleSide
        });

        let geometry = new THREE.SphereGeometry(3, 100, 100);
        cube = new THREE.Mesh(geometry, material);
        cube.position.x = myrandom(-30, 30);
        cube.position.z = myrandom(-20, 20);
        cube.position.y = -20;

        balloons.push(cube);
        scene.add(cube);

Float the balloons Then we can update the Y co-ordinates to move the balloons in upwards direction.

 balloons.forEach(ballon => {
            ballon.position.y += ADD;
            if (ballon.position.y > 20) {
                scene.remove(ballon);
            }
        });

Shooting the balloon We have to convert the (x,y) mouse event co-ordinates to different coordinate system that three.js uses. below code captures the event of mousclick and calculates the coordinates using mouse click event. then using threejs concept of raycast to cast a ray from camera position to the position of coordinates delivered. the raycaster also returns us the all the objects in the ray intersects.

 mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
        rayCast.setFromCamera(mouse, camera);
        intersects = rayCast.intersectObjects(scene.children);
        if (intersects.length > 0) {
            scene.remove(intersects[0].object);
        }

Source code can be found at git