You are to start with bounce.py, which shows an animated ball bouncing off the walls, and make two modifications. This program uses graphics.py, so download it to the same folder in which you saved graphics.py earlier.
twobounce.py: Make a second ball. Have both balls bouncing. If there is a "collision", the balls simply pass through one another.
The first step is to modify bounceInBox() so that it takes a second ball and a second dx,dy. The parameter list might look like this:
def bounceInBox(ball1, ball2, dx1, dy1, dx2, dy2, xLow, xHigh, yLow, yHigh):
Just do both balls, ball1 and ball2, independently in the for i in range(6000) loop. I recommend keeping the ball1 and ball2 variables separate; eg center1, x1, y1 for ball1, though because at this point the balls do not interact this is not actually necessary.
The second step is to modify bounceBall() so that it makes a second center point, and then a second ball, and then calls your modified bounceInBox. I've already added the additional parameters to bounceBall().
collision.py: Modify your twobounce.py so that the balls bounce off one another, changing direction, if they collide.
Here's how to check for a two-ball collision: first get the centers of ball1 and ball2, say at x1, y1 and x2, y2 respectively. You probably did this in twobounce.py. Then, after doing the motion updates (which involve checking for collisions with the walls), test the following:
if (x1-x2)**2 + (y1-y2)**2 <= (ball1.getRadius()+ball2.getRadius())**2:
This checks if the distance between the ball centers is 2*RADIUS (though it works as written if the balls happened to have different radii).
Then, if the two-ball-collision test succeeds, update dx1, dy1, dx2, dy2 as follows (this took a moderate amount of math at my end to work out):
cx = x1-x2
cy = y1-y2
# cx and cy determine the collision centerline
c = math.sqrt(cx*cx +
cy*cy)
s1 = (dx1*cx +
dy1*cy)/c # s1 is the amount of the
(dx1,dy1) velocity along the centerline
dx1 -= 2*s1*cx/c
dy1 -= 2*s1*cy/c
# now do the same for s2 and then dx2 and
dy2
If the balls bounce in crazy directions, or if their speeds change, something is probably wrong with the math here.
For testing, you can improve the odds of a collision by increasing RADIUS, at the top of the file, to 20 or 30.
Here's a diagram that, in theory, shows where the formula above comes from:
bouncing balls
Wednesday:
randomCirclesWhile.py
makePoly.py
Friday:
chooseButton1.py / chooseButton2.py
addEntries.py / addEntries2.py
game demo: invaders.py
This is next week's homework
use of global variables
game options:
Hard: having multiple things at once that are moving. nbounce does this. We will look at that the week after break.
nbounce.py