Collision between player and objects in html5 canvas

I'm making a race-game with html5 and javascript. However I'm struggling with collisions. The car is supposed to stop when it hits one of the objects.

car = player
ctxbigrect = object

This is the code I found on a website, but it doesn't quite seem to work on my game:

if (
      car.x < ctxbigrect.x + ctxbigrect.width 
   && car.x + car.width > ctxbigrect.x 
   && car.y < ctxbigrect.y + ctxbigrect.height 
   && car.height + ctxbigrect.y > ctxbigrect.y) 
{
   console.log("collision detected");
} else {
   console.log("no collision detected");
}

I would it appriciate it a lot if someone could help me out.

1 answer

  • answered 2018-01-16 16:08 zfrisch

    It's easier to think about if you label your points more logically. Honestly if you draw a picture it will help you immensely. The demo below should help you out.

    //setup logical names for the points
    let carLeft = car.x, 
    carTop = car.y, 
    carRight = car.x + car.width, 
    carBottom = car.y + car.height;
    
    let boxLeft = box.x, 
    boxTop = box.y, 
    boxRight = box.x + box.width, 
    boxBottom = box.y + box.height;
    
    //we check if the car is within the radius of the box at all
    //is it past the left border but not the right hand side, 
    //or is it below the top line and above the bottom, 
    //or is the right of the car within the left and right lines of the box 
    //or is the bottom of the car within the bottom and top of the box
    
    if(carLeft >= boxLeft && carLeft <= boxRight || 
    carTop < boxTop && carTop > boxBottom || 
    carRight >= boxLeft && carRight <= boxRight ||
    carBottom >= box.bottom && carBottom <= box.top) {
    //...do whatever
    }
    

    let c = document.querySelector("#myCanvas"), ctx = c.getContext("2d"), car = {
    x: 0,
    y: 5, 
    width: 20,
    height: 10
    }, box = {
    x: 0,
    y: 0,
    width: 30,
    height: 30
    }, flag = false;
    
    function draw() {
    ctx.beginPath();
    ctx.clearRect(0,0,window.innerWidth, window.innerHeight);
    ctx.fillRect(car.x, car.y, car.width, car.height);
    ctx.fillStyle = "rgba(0,250,0, .3)";
    ctx.fillRect(box.x, box.y, box.width, box.height);
    
    let carLeft = car.x, carTop = car.y, carRight = car.x + car.width, carBottom = car.y + car.height;
    let boxLeft = box.x, boxTop = box.y, boxRight = box.x + box.width, boxBottom = box.y + box.height;
    
    
    if(carLeft >= boxLeft && carLeft <= boxRight || carTop < boxTop && carTop > boxBottom || carRight >= boxLeft && carRight <= boxRight || carBottom >= box.bottom && carBottom <= box.top) {
    console.log("hit ", box, car);
    }
    
    if(!flag && box.x < 200) box.x++; 
    if(box.x === 200) flag = true; 
    if(flag && box.x > 0) box.x--;
    if(flag && box.x === 0) flag = false;
    requestAnimationFrame(draw);
    }
    draw();
    <canvas id="myCanvas">