Making boxes bounce around a screen

@debxyz has provided a link to a Java-Processing example, but this is a language independent concept.

Here’s a basic implementation of AABB (rectangle-rectangle collision) collision in Python:

def setup():
    size(500, 500)

def draw():
    background('#0000FF')
    box_1x, box_1y, box_1size = 200, 200, 100 
    box_2x, box_2y, box_2size = mouseX, mouseY, 60 
    
    if (box_2x+box_2size >= box_1x and  # box_2 right-edge over box_1 left-edge?
        box_2x <= box_1x+box_1size and  # box_2 left-edge over box_1 right-edge?
        box_2y+box_2size >= box_1y and  # box_2 bottom-edge over box_1 top-edge?
        box_2y <= box_1y+box_1size      # box_2 top-edge over box_1 bottom-edge?
        ):
        fill('#FF0000')
    else:
        fill('#FFFFFF')
    
    square(box_1x, box_1y, box_1size)
    square(box_2x, box_2y, box_2size)

Of course, you’d have to adapt this for your loop-list set up.

1 Like