It's time to create some geometric snow!
We’re going to start where we left off in part one. If you haven’t completed part one, check it out here.
By the end of this tutorial you’ll add blustery snow to your holiday scene. Check out the final result below!
To create our snowflakes, we’re going to create a class, a way to encapsulate data and logic in object oriented programming.
Let’s look at the basic skeleton of our Snowflake class—the constructor
, which is what we use to make a new Snowflake, and the update
function, which is how we’ll move our Snowflake around.
It’s not much, but it’s something!
We now have a Snowflake that will draw a circle to the screen and set up a timer with setTimer
to move the circle every 50 milliseconds. But a snowflake falling in a straight line isn’t very festive, so let’s see how we can use sine to make it more exciting.
In our Snowflake class, let’s set up a theta
and dTheta
, like like we had earlier. In our update
function, we’ll calculate the x
position based on that theta
, then increment theta
by dTheta
.
Much better!
Now let’s get things ready so we can add many snowflakes.
First, let’s make sure that when a Snowflake leaves the bottom of the screen we remove it and stop calling update
. Otherwise our program will slow down when we have hundreds or thousands of snowflakes. We’ll give each Snowflake an id
that we use when we setTimer
so that when the Snowflake leaves the screen we can call stopTimer
for that Snowflake. In the update
function we’ll always check if the Circle
has moved off the bottom of the screen, and stop things if it has.
Great, now that we have that housekeeping out of the way we can start adding hundreds of Snowflakes.
To make each Snowflake different, we’re going to use Randomizer
to choose a random radius
, dy
, theta
, and x
for each Snowflake. Having some small snowflakes will make them look further away, and having some with faster dy
will give the feeling of a swirling wind.
We’ll use setTimer
to create a new Snowflake every 100 milliseconds using those random values.
Let’s put our code for creating our lights back to create our complete winter scene.
I hope you’ve enjoyed making this holiday scene! There’s a lot you can change to make the program yours—try different values for the Snowflakes’ velocity or amplitude, different colored lights, or come up with your own ways of using geometry to add to the scene!
Share anything you create on Twitter and tag @CodeHS and we’ll share our favorites!
Prefer a video? I walk through the program step by step below.