CircleCollision
From a Processing window,
(Menu bar) File, Examples,
(Maximise) Topics, Motion, CircleCollision
Enter or Double-Click to open the example.
Run the program (Run-icon or ^r)
See the collisions and bouncing.
How can we enhance the program?
- colour the circles?
- More circles?
- Other?
More Circles
See the program has 2 tabs: CircleCollision and Ball.
Click on each and see the code.
For more circles all the changes are in CircleCollision.
See the first Ball definition, line 11, duplicate that line.
(What do you think the 3 numbers are? Some things about the ball?)
It doesn’t work properly if the circles overlap, so change one 100 to 200.
Change the diameter of the first, so you can see which is which (3rd parameter).
Run and watch. Is everything working as expected?
Look at line 29 (about) read carefully. What does it do and what are we missing?
You need multiple lines like that, for 3 circles you need 3 of those lines. (0 1, 0 2, 1 2).
Can you add a 4th circle and make it work? How many checkCollision lines to you need?
What if you had 10 circles, how many would you need? Is there a better way to code these lines?
Colour the circles:
Each ball is a ‘Class’ (definition of a thing) and is defined in the Ball tab.
Ball: (line numbers are approximate)
float radius, m; <- existing line 5
color colour; <- addtional line
(That’s a variable of type color, named colour, to hold the colour for each ball.
Ball(float x, float y, float r_) <- existing line 8
Ball(float x, float y, float r_, color c) <- add colour
(When a ball is created, this is it’s colour parameter.)
m = radius*.1; <- existing line 14
colour = c; <- additional line
(Store the colour parameter from c into colour.
fill(204); <- existing line 135
fill(colour); <- modified to use variable colour
(Try running the program now, see the error message and compare it with the next change below.)
Now the ball will use a defined colour, we need to tell it what colour we want.
In the circleCollision tab:
new Ball(100, 400, 5), <- existing line 13 to:
new Ball(100, 400, 5, color(random(255),random(255),random(255))),
- Add the random colour definition to each ‘new Ball’ line.
- Use fixed colour values if you prefer.
Run the program.
--------------------------------------------------------------------------------------