Skip to main content

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.

https://www.youtube.com/watch?v=K_ukPCLhCR8

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;
    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;
    }

    public void initialize(Point screenBounds) {
        this.screenBounds = screenBounds;

        cloudsBitmap = BitmapFactory.decodeResource(
                parentActivity.getResources(),
                R.drawable.clouds);
        cloudSourceDimensions.right = cloudsBitmap.getWidth();
        cloudSourceDimensions.bottom = cloudsBitmap.getHeight();

        cloudDestinationDimensions.right = screenBounds.x;
        cloudDestinationDimensions.bottom = screenBounds.y;

        jetBitmap = BitmapFactory.decodeResource(
                parentActivity.getResources(),
                R.drawable.jet);
        jetSourceDimensions.right = jetBitmap.getWidth();
        jetSourceDimensions.bottom = jetBitmap.getHeight();

        jetScaledDestinationWidth = screenBounds.x / 5;

        int jetScaledDestinationHeight = (int)((float)jetScaledDestinationWidth
                * ((float)jetSourceDimensions.height() / (float)jetSourceDimensions.width()));

        jetDestinationDimensions.left = screenBounds.x;
        jetDestinationDimensions.right = jetDestinationDimensions.left + jetScaledDestinationWidth;
        jetDestinationDimensions.top = (int)(screenBounds.y / 2d - jetScaledDestinationHeight / 2d);
        jetDestinationDimensions.bottom = jetDestinationDimensions.top + jetScaledDestinationHeight;

        jetScaledMovementSpeed = screenBounds.x / 50;
        if(jetScaledMovementSpeed <= 0) {
            jetScaledMovementSpeed = 1;
        }
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        long currentMilliseconds = SystemClock.uptimeMillis();
        long pastCurrentCanvasDrawDifference = currentMilliseconds - lastFrameTimeInMilliseconds;
        lastFrameTimeInMilliseconds = currentMilliseconds;

        canvas.drawColor(Color.BLACK);

        canvas.drawBitmap(cloudsBitmap, cloudSourceDimensions, cloudDestinationDimensions, null);

        jetDestinationDimensions.left -= jetScaledMovementSpeed;
        jetDestinationDimensions.right -= jetScaledMovementSpeed;
        canvas.drawBitmap(jetBitmap, jetSourceDimensions, jetDestinationDimensions, null);

        if(jetDestinationDimensions.left < -jetScaledDestinationWidth) {
            jetDestinationDimensions.left = screenBounds.x;
            jetDestinationDimensions.right = jetDestinationDimensions.left + jetScaledDestinationWidth;
        }

        if(this.getVisibility() == View.VISIBLE) {
            if(pastCurrentCanvasDrawDifference == 0) {
                postDelayed (
                    new Runnable() {
                        @Override public void run() {
                            invalidate();
                        }
                    }, currentDrawRefreshInterval
                );
            } else {
                if(pastCurrentCanvasDrawDifference < currentDrawRefreshInterval) {
                    postDelayed (
                        new Runnable() {
                            @Override public void run() {
                                invalidate();
                            }
                        }, currentDrawRefreshInterval - pastCurrentCanvasDrawDifference
                    );
                } else {
                    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.



Popular posts from this blog

ChatGPT is a new, and faster, way to do programming!

Currently ChatGPT is in a free “initial research preview” . One of its well known use cases at this point is generating software code. I’ve also just used it to write most of this article… Well, actually a future article about cleaning up SRT subtitle files of their metadata faster than I have been by hand with Notepad++ and its replace functionality. Update: I recorded a screencast of writing the SRT subtitle cleaner application loading and processing portion. I relied heavily on ChatGPT for code. It was a fun process! https://youtu.be/TkEW39OloUA ChatGPT, developed by OpenAI, is a powerful language model that can assist developers in a variety of tasks, including natural language processing and text generation. One such task that ChatGPT can help with is creating an SRT cleaner program. SRT, or SubRip Subtitle, files are commonly used to add subtitles to video files. However, these files can become cluttered with unnecessary information, such as timing lines or blank spaces. To clean...

Theme error in 2010s Android App after AppCompat Migration

I plan on releasing a lot of my old work as GPL open source, but most of it has aged to the point that it no longer functions, or if it does work it’s running in compatibility mode. Basically it’s no longer best practices. Not a good way to start off any new public GPL projects, in my opinion. The current project I’m working on is an Android app that calculates star trails meant to help photographers get or avoid that in their night time photos. For now I’m going to skip some of the import process because I didn’t document it exactly. It’s been mostly trial and error as I poke around Android Studio post import. The Android Studio import process… Removing Admob Google Play code before the project would run at all. After removing dependencies, it kind of worked, but when running it in the emulator it shows a pop-up message saying that the app was developed for an old version of Android. Going through the process of updating code to match current best practices… I had the IDE convert the ...

Printing to file in Linux WINE

I noticed that this post has been sitting as a draft since 2011. At this point I have no idea if it’s useful or what I was even doing, but I might as well make it public in case someone can find it helpful! So I’ve been trying to get one of those PDF print drivers working in WINE without success. I then came upon a process that might work. When printing you need to select the checkbox “Print to file” that creates a .prn file. Just Linux things... I was using a program that only has printing facilities, but I want to export around 100 pages of text and images. Once you have the .prn (postscript) file, you can do any number of things to it. In my case I want the postscript file to be converted to HTML. I am also considering PDF format because that has more conversion options to eventually get me to HTML or plain text. sudo apt-get install cups-pdf Or it looks like that package might have changed to this… sudo apt-get install printer-driver-cups-pdf Where PDFs would be generated in /home/...