Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int numberOfCircles;
- int lineX;
- //is the line moving right? To check if the line is moving left you just check if it's NOT moving right (!isLineMovingRight)
- boolean isLineMovingRight;
- //The index of the array is always the number of the circle. So if I do xPosition[5] I get the x value for the 6th circle. Remember, arrays start at 0, not 1!
- int[] xPositions;
- int[] yPositions;
- int[] radii;
- void setup() {
- size(500, 500);
- background(0);
- ellipseMode(CORNER);
- lineX = 0;
- numberOfCircles = 100;
- isLineMovingRight = true;
- xPositions = new int[numberOfCircles];
- yPositions = new int[numberOfCircles];
- radii = new int[numberOfCircles];
- //I've put the whole generating circle code into its own method, so I can call it in other places without re-writing it again. Specifically, we need it again when the line reaches one of the window borders.
- calculateCircles();
- }
- void draw() {
- background(50);
- //code to draw circles and check if they should be moved
- noStroke();
- fill(255, 125);
- for (int i = 0; i < numberOfCircles; i++) {
- if (isLineMovingRight && xPositions[i] == lineX) {
- xPositions[i]++;
- }
- //when the line is moving left, we have to add the radius to the xPosition of the circle. To see what happens if we don't, just remove the "+radii[i]". This is because the "corner" of each circle is in the top left.
- if (!isLineMovingRight && xPositions[i]+radii[i] == lineX) {
- xPositions[i]--;
- }
- //using the circle function instead of the ellipse function, well, because uh that's what it's made for. Of course you could just use ellipse and add another argument with radii[i] again *shrug*
- circle(xPositions[i], yPositions[i], radii[i]);
- }
- //code to draw and move line
- stroke(255, 0, 0);
- line(lineX, 0, lineX, height);
- //another way to write the following 5-line-if-else-statement would be:
- //lineX = isLineMovingRight ? lineX+1 : lineX-1
- //the question mark is called a "ternary operator". You'll use it all the time once you've learned about it because it unclutters the code greatly. In this case it saves 4 lines of code!
- if (isLineMovingRight) {
- lineX++;
- } else {
- lineX--;
- }
- lineX = isLineMovingRight ? lineX-1 : lineX+1
- //if the line hits either the right or left side, we need to switch direction and calculate new circle positions.
- if (lineX == width || lineX == 0) {
- isLineMovingRight = !isLineMovingRight;
- calculateCircles();
- }
- }
- void calculateCircles() {
- for (int i = 0; i < numberOfCircles; i++) {
- radii[i] = ceil(random(1, 30));
- yPositions[i] = ceil(random(0, height-radii[i]));
- xPositions[i] = ceil(random(0, width-radii[i]));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement