Today, we’re going to start a new series about particles in
Metal. Since most of the time particles are tiny objects, we are not usually concerned about their geometry. This makes them fit for a compute shader because later on we will want to have granular control over particle-particle interactions and this is a case fit for a high degree of parallelism control which a compute shader allows us to have. Let’s use the last playground we worked on when we did ambient occlusion and continue from there. That playground is useful here because it already has a time variable that the
CPU passes to the
GPU. Let’s start with a fresh Shaders.metal file, and just give the background a nice color:
Next, let’s create a particle object that only has a position (center) and a radius:
We also need a way to know where the particle is on the screen, so let’s create a distance function for that:
Inside the kernel, right above the last line, let’s create a new particle and place it at the top of the screen, midway on the
X axis. Give it a radius of
Note: we used the
Ycoordinate of the particle but this is only a trick to show basic movement. Soon, we will replace this variable with a coordinate that changes under the laws of physics.
Replace the last line of the kernel with these lines and run the app. You should see the particle falling down at a steady rate:
The particle, however, will keep going down forever. To make it stop at the bottom, enforce this condition right before creating the particle:
uvvariables go from
0-1so we create a
stoppoint which is the window height less the particle radius.
That was a very basic collision detection rule. If you run the app, you should be able to see the particle falling down uniformly and stopping at the bottom, like this:
Next time we will go deeper into particle dynamics and implement the laws of motion from physics. The source code is posted on
Github as usual.
Until next time!