Ask coding questions

← Back to all posts
Collision detection not working very good.
PowerCoder (741)

It'll say game over before you even touch the pipes.
I want to know if there's a collision with the pipe and the bird. And if there is run this code:

mwilki7 (1134)

I derived this function:

function checkCollision(a, b)
    return (a.x < b.x + b.width  &&
            a.x + a.width > b.x  &&
            a.y < b.y + b.height &&
            a.y + a.height > b.y);

From this page:


var rectA = {x: 10, y: 10, width: 10, height: 10};
var rectB = {x: 10, y: 15, width: 10, height: 10};

if (checkCollision(rectA, rectB))
    console.log('Collision detected');
PowerCoder (741)

@mwilki7 I looked at the same post and did this:

function collision(el1_el, el2_el) {
    var rect1=window.getComputedStyle(el1_el);
    var rect2=window.getComputedStyle(el2_el);

    if (remove_px(rect1.left) < remove_px(rect2.left) + remove_px(rect2.width) &&
        remove_px(rect1.left) + remove_px(rect1.width) > remove_px(rect2.left) &&
        remove_px( < remove_px( + remove_px(rect2.height) &&
        remove_px( + remove_px(rect1.height) > remove_px( {
        return true;
    } else {
        return false;
EduardFaus (3)

The problem is very simple i took a look at your assets and images and immediately saw the problem. If you look at the bird image the bird is in the middle but theres alot of empty space. If you want to fix this crop the image as much as you can so the bird is still visible. I hope this helps.

PowerCoder (741)

@EduardFaus It is cropped as much as you can. All that black area you see is a transparent background.

shaanbomb123 (9)

yes I noticed that when I played your game in one of your other posts, I think it has to do with the sizing of your collision box.

PowerCoder (741)

@shaanbomb123 It doesn't. They are both transparent images. I also don't have sizing for my collision box. HTML already knows the width and height of the element.

shaanbomb123 (9)

oh ok then maybe some code is over powering it

MrEconomical (2304)

you don't need a fancy collision library. it's actually very simple to implement collision detecting, merely get the coordinates of rectangles and check if they are overlapping.

PowerCoder (741)

@MrEconomical That requires heavy math. And I'm already trying that as you can see in collision.js.

MrEconomical (2304)

@PowerCoder no not really, you can check if rectangles collide with one line of code

xxpertHacker (931)

@MrEconomical Why didn't you post the line of code?

CodingCactus (4333)

if touching the pipes:
delay for a bit
tell them they died


PowerCoder (741)

@CodingCactus It'll still tell you that you died but just delayed.

CodingCactus (4333)

@PowerCoder oh, ok. That is all that i know