简体   繁体   中英

Javascript game collision detection

I realize this may be a common question however after looking at the other answers i'm not sure my implementation benefits from the answers.

My game has the player shooting from its XY position towards the mouse XY position, with the enemies falling linearly down the Y axis.

However it seems only the first shot or a random shot in on the screen will sometimes hit and remove an enemy, with some bullets passing straight through with a direct hit and not invoking the removal of the enemy.

The game can be seen here: https://liammorgan.github.io/wave_defence/

And the snippet for hit detection is here, which works around 20% of the time, or on the first bullet shot.

Each shot has an X,Y,bulletSpeed, xVelocity, yVelocity

Each enemy has an X,Y,speed

shot.js -
this.hit = function() {
        for(enemy in enemies) {
            let e = enemies[enemy];
            if(e != null) {             
                if(this.x+this.size > e.x && this.x-this.size < e.x && 
                this.y+this.size > e.y && this.y-this.size < e.y) {
                    enemies[enemy] = null;
                    return true;                    
                } else {
                    return false;
                }
            }
        }
    }

sketch.js -
let shots = [];
let enemies = [];
if(player.lives > 0) {
        player.update();
        player.draw();
        for(shot in shots) {
            let s = shots[shot];
            if(s != null) {                
                if(s.hit() && s != null) {
                    shots[shot] = null;
                    continue;
                }
                shots[shot].update();
                shots[shot].draw();
                if(s.remove() && s != null) {
                    shots[shot] = null;
                }
            }
        }
    }

It seems to me that in your collision logic, you're not accounting for the size of the enemy itself. So for the collision to count, the shot has to PERFECTLY hit almost the exact center of the enemy.

A better way to do it would be to measure the distance from the center the bullet to the center of the enemy, and check that to their known sizes, since both the enemy and bullet are circles. This also means that you would have to include a radius or size field to the enemy objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM