So now that we have vectors, we need to do something with them. We're going to use the concept of a Particle. This is supposed to represent a tiny object in our world that is affected by physics. For this reason, it has a position, velocity, acceleration, etc.
For starters, let's define the basic particle:
A few things to note:
- It's an abstract class. Depending on your use of it, it doesn't have to be. This is actually a ready-to-go particle; it just doesn't have anything in terms of visuals attached to it.
- Note the concept of "Age" in there (lines 3, 8 and 9). A particle lives for a while, then dies. It doesn't have to - but for most particle based simulations, you do want that.
- The "Radius" property is supposed to indicate the size of the particle. It could be argued that this belongs in a subclass.
The only real point of interest is the RunFrame method on line 26. This is the key to the whole physics simulation. Remember I said that it's down to two lines of code? Those are 29 & 30 - the rest is fluff. We call this method every frame, telling it how long since the last call, and it will move the given particle in the right direction by the right amount.
So now that we have this abstract particle, let's use it to make something a little more specific to our fireworks demo:
You'll see we're only adding two things, both tangential to the core of this topic, but we need a little bling: The particle's color and opacity - the latter being a function of its age; it dims as it grows older.
Oh, and the Custom property. I'll get to that later; it's totally an implementation detail and not necessarily a pretty one.
So, what are we missing at this point?
- We need a page to put all this on, with some UI controls for playing with variables.
- We need some way of rendering the particles to the page (there's no drawing code above - I prefer not to put it in these classes).
- We need to actually create particles with positions and velocities that will suggest some kind of fireworks.
- We need code to tie it all together; the rendering, the UI, the particle generation.
Here's a screenshot of what the end result will look like:
(Yeah, no beauty contest winner - but it's effective :))