I started
playing around with the background image example, I mainly changed the line
moving down into multiple ellipses moving downwards, giving the impression of
rain.
First, I
defined three arrays for a certain amount of raindrops which store the speed, y and x coordinate of each raindrop.
As part of
the block of the setup function, I kept the background image of the space
station on the moon and assigned a value to all elements of the arrays (using a
for-loop), some of which are random (like speed and x coordinate), one is a
constant (y coordinate, which I initialized to zero).
Within the
draw function, I created another for-loop, in which the y coordinate is
increased by the speed assigned to the individual raindrop in each repetition
of the draw function.
To make the
raindrops reappear once they reach the bottom edge of the picture, I introduced
an if-clause (similar to the clause that was already there in the example) which resets the x value to a random value and the y value to
zero.
Here is the original code:
/**
* Background Image.
*
* This example presents the fastest way to
load a background image
* into Processing. To load an image as the
background, it must be
* the same width and height as the program.
*/
PImage bg;
int y;
void setup()
{
size(640, 360);
// The background image must be the same size
as the parameters
// into the size() method. In this program,
the size of the image
// is 640 x 360 pixels.
bg = loadImage("moonwalk.jpg");
}
void draw()
{
background(bg);
stroke(226, 204, 0);
line(0, y, width, y);
y++;
if (y > height) {
y = 0;
}
}
Here is my code:
/**
* This is an example of a loop which produces
multiple objects with random values on top of a background image.
*/
PImage bg;
int
amountOfRaindrops = 10;
float[]
speed = new float[amountOfRaindrops];
float[] x =
new float[amountOfRaindrops];
float[] y =
new float[amountOfRaindrops];
void setup()
{
size(640, 360);
bg = loadImage("moonwalk.jpg");
// initializes start values for raindrops
for (int i = 0; i< amountOfRaindrops;
i++) {
// raindrops are colored with a shade of
blue
fill(0,0,random(255));
speed[i]=random(10,20);
x[i]=random(width);
// y will change in draw function
y[i]=0;
}
}
void draw()
{
background(bg);
for (int i = 0; i< amountOfRaindrops;
i++){
// if statement resets raindrop to the top
of the image if raindrop reached the bottom edge
if (y[i]>height) {
x[i]=random(width);
y[i]=0;
}
// for each execution of the for loop, the
speed will be added to the y position of each raindrop
y[i] += speed[i];
// a raindrop will be drawn with a hard
coded size and changing x and y values.
ellipse(x[i],y[i],20,30);
}
}
Very nice and well done
ReplyDelete