Building a physics engine to get things moving

Create a new package private class called PhysicsEngine and add the following code.

class PhysicsEngine {

   // This signature and much more will 
   //change later in the project
   boolean update(long fps, ParticleSystem ps){

        if(ps.mIsRunning){
            ps.update(fps);
        }

        return false;
    }

   // Collision detection method will go here

}

The PhysicsEngine class only has one method for now, update. By the end of the project it will have another method for checking collisions. The signature of the update method receives the frames per second and a ParticleSystem. The code simply checks if the ParticleSystem is running and if it is calls its update method and passes in the required fps.

Now we can create an instance of the PhysicsEngine and call it supdate method each frame. Create an instance of the PhysicsEngine class with this highlighted line of code as a member of the GameEngine class:

…
private GameState mGameState;
private SoundEngine mSoundEngine;
HUD mHUD;
Renderer mRenderer;
ParticleSystem mParticleSystem;
PhysicsEngine mPhysicsEngine;

Initialize the mPhysicsEngine with this highlighted line of code in the GameEngine constructor.

public GameEngine(Context context, Point size) {
   super(context);

   mUIController = new UIController(this, size);
   mGameState = new GameState(this, context);
   mSoundEngine = new SoundEngine(context);
   mHUD = new HUD(size);
   mRenderer = new Renderer(this);
   mPhysicsEngine = new PhysicsEngine();

   mParticleSystem = new ParticleSystem();
   mParticleSystem.init(1000);
}

Call the update method of the PhysicsEngine class from the run method of the GameEngine class, each frame, with this highlighted line of code

if (!mGameState.getPaused()) {
   // Update all the game objects here
   // in a new way

   // This call to update will evolve with the project
   if(mPhysicsEngine.update(mFPS, mParticleSystem)) {
          // Player hit
          deSpawnReSpawn();
   }
}

The update method of the PhysicsEngine class returns a boolean. Eventually this will be used to detect if the player has died. If it has then the deSpawnReSpawn method will rebuild all the objects and reposition them. Obviously deSpawnReSpawn doesn't do anything yet. The key part of the code just added is that within the if condition being tested is the call to mPhysicsEngine.update that passes in the frame rate and the particle system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.248.0