2D 碰撞检查 JavaScript,无法正常工作



我一直在尝试二维矩形碰撞,但我偶然发现了一个错误,即使经过一个多小时的调整,我也无法修复。

碰撞可以很好地向上、向下和向左移动。但是右侧会导致玩家上升到碰撞的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;
}
}
}

冲突.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);
}

}

编辑:更改了一些代码(没有解决问题(

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

目标2位置=(2,0(尺寸=(2,0(

0<2+2=真实

0+2>2=错误

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

尝试:

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 
}

最新更新