A.I, Data and Software Engineering

Game Frame rate and character animations (part 2)

G

In part 1, we covered the principle of game frame rate and a useful game programming pattern for performance. This part shows the detailed implementation of a game scene with hundreds of moving characters using Android Studio and Kotlin.

Image asset

This game uses a free image from wild-refuge.net.

Xmas girl 3 (URL)

You can download any similar image (4 x 4 frames) and place it in the res/drawable of Android project.

The gameloop interface

For simplicity, we create a minimal game loop. In a real game, you should implement additional methods to synchronize with view life-cycle (Android/iOS).

The Sprite class

This class handle the appearance of a character as well as its movement. It has its own thread to update the walking animation. The declaration of the class and some related fields look like this:

There will be two animations in this class, the walking animation and the movement. The walking animation has 4fps meanwhile the moving pace is 1 pixel every update. We continue with a constructor which prepare the bitmap and frame to draw. The draw method draws an src frame to the dst rectangle. The setDst method set the character to a specified location.

The function move will be called within the update method of class GameView.

The GameView class

This class manage all the game objects including sprites, obstacles, etc. Similar to Sprite class, this class has its own thread where we implement a game loop.

We implement the update and draw methods from the game loop interface to update and draw all sprites stored in an array list.

Next, we implement the game loop as mentioned in part 1.

There are synchronized blocks to avoid the concurrentmodificationexception as we add new sprites with taps.

We also added some code for gesture detection. A single tap will place a new sprite on the screen and a double-tap will change all sprites’ moving direction.

And the animation result

Hundreds of sprites walking with no lag - 60FPS
Hundreds of sprites walking with no lag

To sum up

This article demonstrates the implementation of a game loop pattern for enhancing the animations of a video game. You can find the source code below.

Source code: Github

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest

Newsletters

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.