Home > Blockchain >  JavaScript does not detect collisions (game)
JavaScript does not detect collisions (game)

Time:01-03

I'm following a JavaScript tutorial from a german YouTuber. I have the same code as he has but for some reason, the program doesn't print "Collision!!!" into the console. I have the same code as he but my code does not work. His code it works. I don't know how to fix this. Please help!

Here is the URL to the video if anyone want to compare my and his code (It is already at the correct timestamp): https://youtu.be/eWLDAAMsD-c?t=5041


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Space Fight</title>
    <style>
        canvas {
            background-color:rgba(0, 0, 0, 0.8);
        }
    </style>

    <script>
        let KEY_SPACE = false; // 32
        let KEY_UP = false; // 38
        let KEY_DOWN = false; // 40
        let canvas;
        let ctx;
        let backgroundImage = new Image();
        let divisor = 4


        let rocket = {
            x: 100,
            y: 200,
            width: 640 / divisor,
            height: 366 / divisor,
            src: "assets/img/rocket.png"
        };
        let ufos = []

        document.onkeydown = function(e) {
            if (e.keyCode == 32) { // SPACE KEY WAS PRESSED
                KEY_SPACE = true;
            }
            if (e.keyCode == 38) { // UP-ARROW KEY WAS PRESSED
                KEY_UP = true;
            }
            if (e.keyCode == 40) { // DOWN-ARROW KEY WAS PRESSED
                KEY_DOWN = true;
            }
        }

        document.onkeyup = function(e) {
            if (e.keyCode == 32) { // SPACE KEY WAS RELEASED
                KEY_SPACE = false;
            }
            if (e.keyCode == 38) { // UP-ARROW KEY WAS RELEASED
                KEY_UP = false;
            }
            if (e.keyCode == 40) { // DOWN-ARROW KEY WAS RELEASED
                KEY_DOWN = false;
            }
        }

        function startGame() {
            canvas = document.getElementById("canvas");
            ctx = canvas.getContext('2d');
            loadImages();
            setInterval(update, 1000 / 60);
            setInterval(createUfos, 5000);
            setInterval(checkForCollision, 1000 / 60);
            draw();
            //calculate
        }

        function checkForCollision() {
            ufos.forEach(function(ufo) {
                if (
                    rocket.x   rocket.width > ufo.x && 
                    rocket.y   rocket.height > ufo.y && 
                    rocket.x < ufo.x && 
                    rocket.y < ufo.y
                    ) {
                    console.log('Collision!!!');
                }
            });
        }

        function createUfos() {
            let ufo = {
            x: 800,
            y: 200,
            width: 640 / divisor,
            height: 324 / divisor,
            src: "assets/img/ufo.png",
            img: new Image()
        };
            ufo.img.src = ufo.src;
            ufos.push(ufo);
        }

        function update() {
            if (KEY_UP) {
                rocket.y -= 2;
            }
            if (KEY_DOWN) {
                rocket.y  = 2;
            }

            ufos.forEach(function(ufo){
                ufo.x -= 4
            });
        }

        function loadImages() {
            backgroundImage.src = 'assets/img/background.jpg';
            rocket.img = new Image();
            rocket.img.src = rocket.src;


        }

        function draw() {
            ctx.drawImage(backgroundImage, 0, 0);
            ctx.drawImage(rocket.img, rocket.x, rocket.y, rocket.width, rocket.height);
            ufos.forEach(function(ufo) {
                ctx.drawImage(ufo.img, ufo.x, ufo.y, ufo.width, ufo.height);
            })

            requestAnimationFrame(draw);
        }
    </script>
</head>
<body onl oad="startGame()">
    <canvas id="canvas" width="720" height="480"></canvas>
</body>
</html>

This is the file-structure: https://i.stack.imgur.com/iTl9E.png

CodePudding user response:

You can check collision like this:

function dotInBox (dotX, dotY, box) {
    const {x, y, w, h} = box
    return x <= dotX && dotX <= x   w && y <= dotY && dotY <= y   h
}

if (dotInBox(b.x, b.y, a) ||
    dotInBox(b.x   b.w, b.y, a) ||
    dotInBox(b.x, b.y   b.h, a) ||
    dotInBox(b.x   b.w, b.y   b.h, a)) {
    // Collision
}

Function dotInBox checks if any dot in your square given by coordinates and dimensions. By checking every dot of other square we can say that collision happened.

CodePudding user response:

Your collision check condition was not correct. Update it as follow.

(rocket.x   rocket.width > ufo.x && 
rocket.x < ufo.x) ||
(rocket.y   rocket.height > ufo.y && 
rocket.y < ufo.y)

Your code was like this.

rocket.x   rocket.width > ufo.x && 
rocket.y   rocket.height > ufo.y && 
rocket.x < ufo.x &&
rocket.y < ufo.y
  • Related