2D碰撞检查javascript,无法正常运行

时间:2018-08-06 17:48:06

标签: javascript html collision-detection

我一直在尝试2D矩形碰撞,但是即使经过一个多小时的调整,我仍然遇到无法解决的错误。

碰撞在上下左右都可以正常工作。但是右边导致玩家上升到碰撞的y值。该代码与左侧站点完全相同(正确镜像。我认为)

var player = new Player(50,50,100,0.3,false,0,0)
var playerCollision = new Collision(player.x,player.y,64,64);
var ground = new Collision(0,500,300,100);
var wall = new Collision(200,400,100,100);
var wall2 = new Collision(0,400,100,100);
var collisions = [ground,wall,wall2];


for (i=0;i<collisions.length;i++) {
        if (collisions[i].checkCollision(playerCollision)) {
            if (collisions[i].x - playerCollision.x > 0 && playerCollision.x + playerCollision.width > collisions[i].x-1 && playerCollision.y+playerCollision.height-20 > collisions[i].y) {
            player.dx = 0;
            player.x = collisions[i].x-64;
        } else if ((collisions[i].x + collisions[i].width)- playerCollision.x < 0 && playerCollision.x < collisions[i].x+collisions[i].width+1 && playerCollision.y+playerCollision.height-20 > collisions[i].y) {
            player.dx = 0;
            player.x = collisions[i].x+collisions[i].width;
        } else if (collisions[i].y - playerCollision.y+playerCollision.height > 0) {
            player.dy = 0;
            player.y = collisions[i].y-64;
        } else if ((collisions[i].y+collisions[i].height) - playerCollision.y < 0) {
            player.dy = 0;
            player.y = collisions[i].y+collisions[i].height;
        }
    }
    }

Collision.js:

function Collision(x,y,width,height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;

this.checkCollision = function(other) {
        if (this.x < other.x + other.width &&
            this.x + this.width > other.x &&
            this.y < other.y + other.height &&
            this.height + this.y > other.y) {
            return true
         } else {
             return false;
         }
}

this.show = function() {
    ctx.strokeStyle = "#38ff35";
    ctx.strokeRect(this.x,this.y,this.width,this.height);
}

}

编辑: 更改了一些代码(无法解决问题)

1 个答案:

答案 0 :(得分:0)

obj1 位置=(0,0) 尺寸=(2,0)

obj2 位置=(2,0) 尺寸=(2,0)

0 <2 + 2 =正确

0 + 2> 2 =假

这已经表明您的支票在数学上没有意义。这两个块应该重叠,但返回false

尝试:

if (this.x + this.width < other.x - other.width ||
this.x - this.width > other.y + other.width ||
this.y + this.height < other.y - other.height ||
this.y - this.height > other.y + other.height)
{
    no collisions 
}