Thursday, April 29, 2010

2D Particles: Part 2 Basic Particle

Welcome to the second part, first actual programming part, of my 2d particle engine tutorial. Today we will be creating a basic particle class which will be expanded later but for now it will be simple and clean. Now lets begin, first create a new class named Particle and add the following variables into it. All of these variables are private because we just need them in this class except for IsAlive which we will use to destroy the particles later.
Lets go over each variable. Texture is just the texture of the particle that we will also use to calculate origin. Position is the position that our particle is currently at. Velocity is how fast our particle is moving, more on this later. Rotation is the current rotation of the particle and rotation speed is how fast we are rotating. LifeTime is how long our object will be alive when we first set it and lifeLeft is how much time is actually left before we destroy our particle. IsAlive is whether or not the particle still has time left. This is pretty easy so far, now were going to add the constructor which we will use in a different class to create our particle. We basically want to set all the variables in the constructor because its easier than assigning each value in our other class.
For now we will set rotation to 0 we might change this later so that each particle has a random starting rotation. Initially lifeLeft and lifeTime will be the same, you could just use one variable for this but I split it into 2 because we will need both of them later. Our origin will be the center of our texture. Next we have to add in a function that will update our particle otherwise it would be boring. In our update method we basically want to do 4 things, subtract how much time has elapsed, move the particle with our velocity, rotate with our rotation speed. We also want to check to see whether or not our particle has any time left, otherwise we kill it. We could have our game time as a parameter but instead were going to use a float that represents how much time has elapsed, dt stands for delta time which is the change in time. The reason for this is because the elapsed time is all we really need to know.
This is just the start of our update method as it will get more complex later. But for the final piece of our particle class were going to add in a draw method to draw the current particle. This is just like in the 2d animation tutorial except we don't have a source rectangle so we just set that to null. This will not change much throughout making this engine.
Well that is it for the first part of our particle engine next we will add in a basic particle engine class to create and draw our particles. Any comments, questions or suggestions are appreciated.

You are free to use or modify this source in any way it is for learning purposes.

No comments:

Post a Comment