Android: Basic game loop with scaled graphics.

In this article I go over implementing a simple game loop with a custom view. The standard draw method is used with some timing checks so that we can get an approximately consistent refresh rate. This is a somewhat simple way to get started without having to use something OpenGL.

The full source code is on GitHub.

The main activity handles the creation of our custom view and passes along screen size information once it’s available. This is a key step because it allows us to get that screen information before the view actually starts being displayed. I have a previous tutorial on just that here so I am going to omit the main activity code and the related xml layout file.

If you want an exact game update loop structure, you might need further restrict any numeric changes in your game specifically by time rather than having them in the middle of the draw loop that is approximately updated on a given time frame. I haven’t done any testing to verify if that’s needed or not. Also, read up on Draw() to see if it does automatic calls which could give odd results. I’ve been using this in a simple 2d game I’m making and it so far appears to be good enough. Though, I might spend some time checking it out after I have the game fully implemented. I don’t thing timing will be a big issue in what I’m making.

Here is our custom view code:

public class ViewMain extends View {
    Activity parentActivity = null;

    //monitors game time per round
    long currentDrawRefreshInterval = 50;
    long lastFrameTimeInMilliseconds = 0;

    Point screenBounds = null;

    Bitmap cloudsBitmap = null;
    Rect cloudSourceDimensions = new Rect();
    Rect cloudDestinationDimensions = new Rect();

    Bitmap jetBitmap = null;
    Rect jetSourceDimensions = new Rect();
    Rect jetDestinationDimensions = new Rect();
    int jetScaledDestinationWidth = 0;

    int jetScaledMovementSpeed = 0;

    public ViewMain(Context parentActivityContext) {
        super(parentActivityContext);
    }

    public ViewMain(Context parentActivityContext, Activity parentActivity) {
        super(parentActivityContext);
        this.parentActivity = parentActivity;
    }

    /***
     * this function is called by the parent activity once screen bounds are calculated
     * this is where all code to initialize something like a game would go
     */
    public void initialize(Point screenBounds) {
        this.screenBounds = screenBounds;

        //load the cloud bitmap so we can display it on screen (drawable-nodpi)
        cloudsBitmap = BitmapFactory.decodeResource(
                parentActivity.getResources(),
                R.drawable.clouds);

        //save the width and height of the bitmap because we need that
        //as a rect every it will be drawn to the screen
        cloudSourceDimensions.right = cloudsBitmap.getWidth();
        cloudSourceDimensions.bottom = cloudsBitmap.getHeight();

        //have out bitmap scaled to the entire screen when drawn
        cloudDestinationDimensions.right = screenBounds.x;
        cloudDestinationDimensions.bottom = screenBounds.y;

        //load the jet bitmap so we can display it on screen (drawable-nodpi)
        jetBitmap = BitmapFactory.decodeResource(
                parentActivity.getResources(),
                R.drawable.jet);

        jetSourceDimensions.right = jetBitmap.getWidth();
        jetSourceDimensions.bottom = jetBitmap.getHeight();

        //we want a full sized jet graphic to take up 1/5th of the screen when fully visible
        jetScaledDestinationWidth = screenBounds.x / 5;

        //get the scaled height by taking the original image ratio and multiplying it
        //by the new scaled image width we just calculated
        int jetScaledDestinationHeight = 0;
        jetScaledDestinationHeight = (int)((float)jetScaledDestinationWidth
                * ((float)jetSourceDimensions.height() / (float)jetSourceDimensions.width()));

        //set a starter position of the jet off-screen to the right
        jetDestinationDimensions.left = screenBounds.x;
        jetDestinationDimensions.right = jetDestinationDimensions.left + jetScaledDestinationWidth;

        //have the jet fly in the middle of the screen
        //so you get the screens midpoint minus half of the scaled jet's height
        jetDestinationDimensions.top = (int)(screenBounds.y / 2d - jetScaledDestinationHeight / 2d);
        jetDestinationDimensions.bottom = jetDestinationDimensions.top + jetScaledDestinationHeight;

        //have the jet move 1/50th of the screen every update tick
        jetScaledMovementSpeed = screenBounds.x / 50;
        if(jetScaledMovementSpeed <= 0) {
            jetScaledMovementSpeed = 1;
        }
    }

    /***
     * the function where you draw to this view
     * this is called automatically as well as when you call invalidate
     * in our case we call invalidate at specific intervals
     *
     * @param canvas the object that you use to draw with
     */
    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        //get the current system up-time used in getting an average
        //refresh rate and counting down on game time
        long currentMilliseconds = SystemClock.uptimeMillis();

        //see what the difference is between the last update and right now
        long pastCurrentCanvasDrawDifference = currentMilliseconds - lastFrameTimeInMilliseconds;

        //get ready for the next screen update
        lastFrameTimeInMilliseconds = currentMilliseconds;

        //-----------------------------------------------------------------------------------------

        //clear the screen
        canvas.drawColor(Color.BLACK);

        //draw our clouds graphic, filling the entire view
        canvas.drawBitmap(cloudsBitmap, cloudSourceDimensions, cloudDestinationDimensions, null);

        //have the jet bitmap move across the screen
        jetDestinationDimensions.left -= jetScaledMovementSpeed;
        jetDestinationDimensions.right -= jetScaledMovementSpeed;
        canvas.drawBitmap(jetBitmap, jetSourceDimensions, jetDestinationDimensions, null);

        //see if the jet is fully off-screen on the left
        if(jetDestinationDimensions.left < -jetScaledDestinationWidth) {
            //reset the jet's position to be off-screen on the right
            jetDestinationDimensions.left = screenBounds.x;
            jetDestinationDimensions.right = jetDestinationDimensions.left
                    + jetScaledDestinationWidth;
        }

        //-----------------------------------------------------------------------------------------

        //see if this view is visible to the user
        if(this.getVisibility() == View.VISIBLE) {
            //see if we need to wait to update, or just initiate it now for processing
            if(pastCurrentCanvasDrawDifference == 0) {
                //refresh the screen on a fixed interval
                postDelayed (
                        new Runnable() {
                            @Override public void run() {
                                invalidate();
                            }
                        }, currentDrawRefreshInterval
                );
            } else {
                //see how long we have to wait to refresh
                if(pastCurrentCanvasDrawDifference < currentDrawRefreshInterval) {
                    postDelayed (
                            new Runnable() {
                                @Override public void run() {
                                    invalidate();
                                }
                            }, currentDrawRefreshInterval - pastCurrentCanvasDrawDifference
                    );
                } else {
                    //we don't need to wait, so refresh now
                    post (
                        new Runnable() {
                            @Override public void run() {
                                invalidate();
                            }
                        }
                    );
                }
            }
        }
    }
}

A few things to take note of:
– initialize() is called from a ViewTreeObserver.OnGlobalLayoutListener in the main activity. It passes along the screen’s size so that we can do a few calculations before the view starts.

– The game loop works by tracking the number of milliseconds that have passed between calls to draw(). If the current call to the function is over the desired number of milliseconds (50 in this case) then we do a request for another refresh by calling queuing up a call to invalidate(). if(this.getVisibility() == View.VISIBLE) is there to prevent the app from doing updates when the view isn’t visible to the user.

– I load in two bitmaps from the drawable-nodpi folder, which is one you need to add by hand into a project made from scratch. It’s a special folder that tells the Android system to not do any type of automatic scaling to bitmaps. I prefer this because in a game you should be doing your own screen and graphic scaling. If you don’t, you will run into issues in your calculations and with different devices because the Android automatic graphic scaling isn’t exact as far as I can tell. In the long run, it’s much better doing your scaling from your exact number of screen pixels available in the view.

– PNG graphics have automatic transparency and work great. You can use your image editor of choice and get that nice semi-transparency as you want without doing anything like image masks.

– When doing calculations such a division, Java appears to be picky and tends to return results that are logically fixed to a variable’s datatype. You need to force floating point calculations occasionally to get the results you would normally expect should be the result. I did this in the jet graphic scaling and initial positioning. Without typecasting to float in the scaled height calculations, you would get a zero in straight integer calculations.

This entry was posted in Android, Java and tagged , , , , . Bookmark the permalink.