简体   繁体   English

Javascript游戏冲突检测

[英]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. 我的游戏中,玩家从其XY位置朝着鼠标XY位置射击,而敌人则沿Y轴线性下降。

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/ 可以在这里看到游戏: 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. 命中检测的代码段在这里,大约20%的时间有效,或者在第一发子弹上起作用。

Each shot has an X,Y,bulletSpeed, xVelocity, yVelocity 每个镜头都有X,Y,子弹速度,xVelocity,yVelocity

Each enemy has an X,Y,speed 每个敌人都有X,Y,速度

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. 这也意味着您必须在敌人对象中包括“ radius或“ size字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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