Ask coding questions

← Back to all posts
Pygame Rect collision
ash15khng (486)
I tried to use the inbuilt pygame.Rect.colliderect, but it doesn't work. I've been on this for about an hour aaaa help pls
I made my enemy and player classes subclasses of pygame.Rect already, that shouldn't be the problem. In fact the code runs, but the collision never becomes true.

Answered by mwilki7 (643) [earned 5 cycles]
View Answer
mwilki7 (643)

I have a project that does rectangle collision detection.
(starting line 177 in basketball_func.js)
If you can convert this to python format it should work the same.

function checkCollision(a, b)
    // get rid of these four lines if you are not worried about different types of classes colliding
    if (!(a instanceof Entity))
        return false;
    if (!(b instanceof Entity))
        return false;

    var rect1 = {x: a.pos.x, y: a.pos.y, width: a.w, height: a.h}
    var rect2 = {x: b.pos.x, y: b.pos.y, width: b.w, height: b.h}
    if (rect1.x < rect2.x + rect2.width &&
        rect1.x + rect1.width > rect2.x &&
        rect1.y < rect2.y + rect2.height &&
        rect1.y + rect1.height > rect2.y)
        return true;
    return false;   
ash15khng (486)

@mwilki7 Thanks so much! It works!

katyadee (1167)

Hey there! You should add a little more context to your question & the subject line, so it's easier for people to find and answer.

ash15khng (486)

@katyadee Sorry, I'll do that next time.