Create a program that has a ball move around the screen and bounce off the edges.
Draw a stationary ball in the exact center of the screen over a backdrop of any color.
- At the top of your program
- Create three variables:
float xPos // the x position of the ball
float yPos // the y position of the ball
int bSize // the size of the ball
- In setup()
- Set the size of the window
- Give xPos and yPos starting values
- Hint: Use width and height
- In draw()
- Set the background color
- Set the fill color for the ball
- Draw an ellipse at xPos, yPos that is bSize large.
Think:
- We put some things at the top, some things in setup, and some in draw. Why?
- Why don't we just set the ellipse's position directly? Why use a variable?
Give the ball a "speed" and create a system to move it every frame
- At the top of your program
- Create two new variables:
float xSpeed // how fast the ball is moving left (negative) or right (positive)
float ySpeed // how fast the ball is moving up (negative) or down (positive)
- In setup()
- Give xSpeed and ySpeed random values // A good speed is between -2 and 2
- In draw()
- Assign xPos the value of xPos plus xSpeed // Update the new position by adding speed. Creates an animation.
- Assign yPos the value of yPos plus ySpeed
Make the ball smoothly bounce of the edges of the screen
- In draw()
- If your ball is moving right and it is beyond the right edge of the screen, reverse its xSpeed
- It is moving right if its xSpeed is positive
- It is beyond the right edge if xPos is greater than width
- To reverse xSpeed, flip the sign
- Repeat this process for the left, top, and bottom edges.
- Cleaning It Up...
- Your ball is probably looking a little awkward on some of its bounces. We want to make sure it bounces as soon as it hits an edge and never leaves the screen.
- To do so, accommodate for the size of the ball by adding or subtracting half of bSize on each of your bounce conditions.
- Every time the ball bounces, make it go faster.
- Add a new variable that keeps track of how many times the ball bounces
- Print that value to the console each frame
- Add a second ball
- Each ball should only move as long as neither ball has reached 25 bounces.
- When a ball hits 25 bounces, output a message to the console stating which colored ball "wins."
SAMPLE END OF UNIT QUIZ