Particle System Tutorial on Android Part 2

Movement

Adding animation to the existing project is fairly easy. Particle System will need a new method, update()

    // simply have the particles fall at a hard coded gravity rate
    // and when they hit zero, bump them back up to a z of 1.0f
    public void update() {
        for (int i = 0; i < PARTICLECOUNT; i++) {
	    mParticles[i].z = mParticles[i].z - 0.01f;
            if (mParticles[i].z < 0.0f) {
                mParticles[i].z = 1.0f;
            }
        }
    }

All this method does is loop through each particle, and subtract 0.01 from it. If the z position gets lower than zero, simply put the particle back up at a z of 1.0. Now in the main ParticleSystemDemo class, we need to call this method on each onDrawFrame

    public void onDrawFrame(GL10 gl) {
        gl.glClearColor(0, 0, .5f, 1.0f);
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        mParticleSystem.update();
        mParticleSystem.draw(gl);
    }

The update and the draw routines can be in separate threads. In one of the Android talks I watched, the user input, rendering and world simulation are all separate threads. This just keeps the tutorial simple. Another thing to note is that all the particles fall at the same rate, and the rate is based on each frame draw. So on slower machines the particles will fall slower, and fast on faster devices. In a future tutorial I'll add using the framerate to determine how much to move the particles.

I've also refactored some code. After giving it some though, I don't like having to pass in the Random generator to the particle. The particle system should be responsible for creating the particle and assigning it's location. So instead, I created a new constructor which takes in the x,y,z coordinates.

public class Particle {

    // location
    public float x;
    public float y;
    public float z;
	
    public Particle() {	
    }

    // the constructor which also assigns location
    public Particle(float newx, float newy, float newz) {
        super();
        this.x = newx;
        this.y = newy;
        this.z = newz;
    }
}

The source and apk can be found here. The apk is only compiled for Android version 2.1. The most recent code can be found at Bay Nine Studios on Google Code. That's it for now, stay tuned for Part 3