Search code examples
javapaintcomponent

Simulating rain


I am making a game in java and I want to create a simulation of a cloud that is pouring rain. The cloud is supposed to move to the right while raining. Moving the cloud is no problem. It's the rain that I am struggling with.

What I was thinking of doing was with a timer to draw a rectangle, thats supposed to look like falling rain at a random x value inside of the cloud. And then add 1 to the y value of the drop each 100 millisecond. But I don't want to create 100 different rectangles, x variables and y variables for each rain drop.

Any idea how I can accomplish this? Suggestions appreciated!


It is a 2d game.. Sorry.


Solution

  • I would recommend just storing the values as an ArrayList of objects.

    class Raindrop {
        private int x;
        private int y;
    
        public void fall() {
            y--;
        }
    }
    

    Then make an ArrayList with a generic type.

    ArrayList<Raindrop> drops = new ArrayList<Raindrop>();
    

    To make each drop fall,

    for (int i=0; i<drops.length(); i++) {
        drops.get(i).fall();
    }