2
votes

Hello everyone! I'm making a Super Mario Bros clone game with Python and Pygame and I wrote a function that returns True if two rectangles are colliding and False otherwise. So I know how to detect when Mario collides with a monster. Now, I want to know if Mario jumped over the monster, or in other words, it's rect collided on the top side of the monster rect. How do I do that? Here is my code:

The two rectangles collision detection function:

def is_colliding(x, y, w, h, x2, y2, w2, h2):
    if x < x2 + w2 and x + w > x2 and y < y2 + h2 and h + y > y2:
        return True
    return False

The actual checking of it in the main game loop:

while True:
    # other stuff
    if is_colliding(mario.x, mario.y, mario.w, mario.h, goomba1.x, goomba1.y, goomba1.w, goomba1.h):
        goomba1.wounded()

Any help is appreciated. Thank you.

1

1 Answers

2
votes

The one way to solve the problem is to calculate the "direction of movement" For example you can save the previouse step coordinate and if in the current step is_colliding return True and the mario in previous step was under the monster and in previous step the is_colliding returned False than you can decide that the mario falled from above.

# x1,y1,h1,w1 - mario params
# x2,y2,h2,w2 - monster params
# y1_prev - mario previous param
# y2_prev - monster prevoius param
# collide_prev - previous sollision check

def check_above(x1, y1, w1, h1, x2, y2, w2, h2, y1_prev, y2_prev, collide_prev):
    collide = is_colliding(x1, y1, w1, h1, x2, y2, w2, h2)
    if collide and y2_prev + h2 < y1_prev and not collide_prev:
        return True
    else:
        return False 

The logic is simple if in current step mario is colliding and in previous was both not colliding and mario was above the monster then it means that mario collide from above.

NOTE The code will work if the x coordinate is the left bottom corner of the rectangle