Coding a Renderer

As with many of the classes in this chapter, Renderer will be very similar to the earlier project, so we can zip through it and move on.

Create a new class called Renderer then add the following members and constructor.

class Renderer {
    private Canvas mCanvas;
    private SurfaceHolder mSurfaceHolder;
    private Paint mPaint;

    // Here is our new camera
    private Camera mCamera;

    Renderer(SurfaceView sh, Point screenSize){
        mSurfaceHolder = sh.getHolder();
        mPaint = new Paint();

        // Initialize the camera
        mCamera = new Camera(screenSize.x, screenSize.y);
    }
}

The Renderer has the Canvas, SurfaceHolder and Paint instances as we have come to expect. It also has a Camera instance called mCamera. We at last get to code the Camera class when we are done with Renderer.

In the constructor the SurfaceHolder, Paint and Camera instances are initialized.

Now add the getPixelsPerMetre and draw methods.

int getPixelsPerMetre(){
   return mCamera.getPixelsPerMetre();
}

void draw(ArrayList<GameObject> objects, 
        GameState gs, 
        HUD hud) {

   if (mSurfaceHolder.getSurface().isValid()) {
         mCanvas = mSurfaceHolder.lockCanvas();
         mCanvas.drawColor(Color.argb(255, 0, 0, 0));

         if(gs.getDrawing()) {
                // Set the player as the center of the camera
                mCamera.setWorldCentre(
                              objects.get(LevelManager
                             .PLAYER_INDEX)
                             .getTransform().getLocation());

            for (GameObject object : objects) {
               if (object.checkActive()) {
                   object.draw(mCanvas, mPaint, 
                   mCamera);
               }
            }
      }

      hud.draw(mCanvas, mPaint, gs);

      mSurfaceHolder.unlockCanvasAndPost(mCanvas);
   }
}

The getPixelsPerMetre method uses the instance of the Camera class to return the number of pixels that represent a virtual meter in the game world. We will code the Camera class including this method next.

The code in the draw method prepares the surface, checks it is currently OK to draw then sets the camera to whatever the player's location is using the setWorldCentre method. We will code the Camera class including this method next. Then the code loops through all the objects checking which ones are active and drawing them. Then the HUD is drawn and the now familiar unlockCanvasAndPost method is called.

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

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