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