# Making boxes bounce around a screen

Hi, I am relatively new to processing.py and I’ve been stuck on my code for a few days now. Basically I’m trying to make a bunch of boxes bounce around the screen and bounce off of each other if they collide. I’ve written a bit of the code which I’ll share below, but I have no clue were to begin with the collision, boundaries and adding more boxes to my list.

def setup():
global boxes, numBoxes
global canvasWidth, canvasHeight
global i
i = 6
size(800,600)
background(0)
boxes = [[6, 6], [787,11]]
numBoxes = len(boxes)
canvasWidth = 799
canvasHeight = 599

def draw():
global boxes, numBoxes
background(0)
rect(378,250,100,100)
global canvasWidth, canvasHeight
for i in range(0,1):
boxes[i][0] += 3
boxes[i][1] += 2
rect(boxes[i][0], boxes[i][1], 100, 100)

Any help or advice would be greatly appreciated, thank you!

Hello @matt423 !

This may be of interest:

Both of these examples are processing java not python. So use as a basic roadmap for concepts to solve your collision question.

As for adding more boxes. Please explain more specifically what you want to happen. Do you want boxes to appear via user interaction? Please clarify.

Finally, it is much easier to read when code is formatted to look like this:

``````void setup(){
size(400, 400);
}
void draw(){
}
``````

And so, please format using the </> icon in the toolbar.

3 Likes

Hi

Try to draw boxes first in the way you want when do that becomes easier to bouncing

1 Like

@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

Thank you so much, this was a big help!

Hey Matt, my school is doing a similar project, did you figure out how to get the boxes to bounce of each other?

Yeah I added all of my boxes to a nested list and then I just looped through the list (using a for loop), and if they collided from any of the sides then they would move the opposite direction. I implemented the code that tabreturn sent to my code.