Snow/Rain Effect with Corona SDK Graphics 2.0

With the introduction of Graphics 2.0 in Corona SDK, the ability to wrap an infinite amount of times a tile as a fill of a polygon is finally available.
You can use it for several things. While making puzzle games, for example, you can create the levels without using hundreds of images while still making them look good. An example of this can be found in the Angry Birds series, or more prominently in the Bad Piggies spin-off.

What’s cool though, is that you can also move the fill in any way you want, allowing you to create endless looping backgrounds.

In this tutorial we’re going to use this feature to create a lightweight snow/rain effect. Before you could’ve either used a ton of little objects (surely not good for performances), or 2 very big images, moving down and getting back up, in an endless loop (a lot of texture memory wasted). Now you can achieve it with just a 32×32 image, and a rect.

In our main.lua file, let’s start with this:

This will make sure that any fill of any object will repeat itself around the x and y axis. It’s important that any texture loaded follow the ^2 rule (2, 4, 8, 16, 32, 64 and so on) for both width and height. If not, it will show as completely black on your device.

We continue by declaring 2 variables that will hold the speed at which we will move the fill on the x and y axis.

Here we create our rect, as big as the screen (no matter the device), fill it with our tile (“tilerain.png”), and then we scale it down to make sure that it’s not stretched.
Doing so is as simple as dividing the size that we want for the tile (in this case 32×32) for the width and height of the rect.

We’re almost there. If we start the simulator now, we will see our tile repeated for the entire height and width of the screen. Now we just have to move it.

This setup has a few more values to make the snow “wave” on the x axis. You can just comment out the indicated parts if you want to do something else, like rain.
We basically increase the waveEffectValue to use it in our sin function. The sin will return a value between -1 and 1, which we then decrease by multiplying it for a number lower than 1.
Then, we add our xSpeed and ySpeed to our fill to move it. For last, we reset our fill position in case it becomes lower than -1 or greater then 1. This makes sure that we don’t get numbers too high or cause other kind of issues.

Then, let’s make sure that we reset the default values for textureWrapX and textureWrapY.

Done! By changing the proper values we can create a raging torment, or a colorful animated endless background.
We can also give more depth to our snow by creating more layers, moving at different speeds, always with just a 32×32 texture.

You can download this tutorial code directly from here -> Snow and Rain Effect