Search code examples
javascripthtmlcollision-detection

2d collision checking javascript, doesen't work properly


I've been experementing with 2d rectangular collision but i stumbled into an error i can't fix, even after over an hour of tweaking.

Collision works fine up, down and left. but the right causes the player to go up to the y value of the collision. The code is the exact same as the left site (correctly mirrored. I think)

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);
}

}

EDIT: changed some code (didn't fix the problem tho)


Solution

  • obj1 position = (0, 0) dimensions = (2, 0)

    obj2 position = (2, 0) dimensions = (2, 0)

    0 < 2 + 2 = true

    0 + 2 > 2 = false

    this already shows that your check doesn't mathematically make sense. These two blocks should be overlapping but return false

    Try:

    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 
    }