Android SDK: Achieving Movement

In this tutorial, we will run through a quick guide on how to achieve object movement, one of the foundations of game development. We won't be doing anything fancy, just bouncing a ball across the screen. However, the principles in this tutorial can be easily applied in many more complex scenarios. Without further delay, let's jump right in!

The Setup

Before we start to write any code, let's create our basic file structure.

First create your Android project. Name the project "Movement" and match the rest of your project settings with the photo below:

You will notice that the API level is pretty low since all features used here are very basic and have been used since day one in Android.

Next, we will create two more classes for our project. Specifically, the UpdateThread class and MovementView class, which are our Thread and SurfaceView objects respectively. More on these later. Pay attention to the class name and superclass of these classes; I will be referencing these throughout the tutorial.

That's all the set up we've got to do for the project! If everything went OK, your project folder should look like this:

Don't worry about the single error you have at the moment, it will be corrected very soon!

Before we go any further, be warned: all of these snippets of code look extremely long in this format! But do not worry, most of it is just comments for this tutorial. Without the comments it would be less than half the length. Don't let this put you off!

Section One: Coding the Activity

Your application Activity, Movement.java, is the base of your app. It get's called at the very beginning of the app life cycle, and is needed to call into action any other Activity or SurfaceView you might want to run.

Our activity will be very simple. In fact, we will only be editing one line of code! This is all we need to launch our MovementView class.

Step 1: Activity Imports

Step 2: The Class and onCreate Method

This is the first code executed in our app. Note the use of the setContentView() method where we set the app's view to our MovementView class, in which all drawing will take place. We also pass "this" into the constructor.

And thats all we have to do with the Activity class for the rest of the project!

The SurfaceView

What is the SurfaceView? Our SurfaceView is the class MovementView.java. All a SurfaceView does is provide a big drawing pad for our app. In this view we can draw onto the Canvas and it will displace it for us. We will be using this to create a ball from pure code and draw it in a new position everytime the UpdateThread tells it to. Let's jump right in and fix that annoying error created when we started our project by opening up MovementView.java.

Step 3: SurfaceView Imports

Step 4: SurfaceView Class Outline

Notice that our class extends SurfaceHolder.Callback. This is what allows the view to detect things like the surface being created, changed or destroyed - very useful! All steps following this will be the methods and functions that should be placed inside this class. We will also define our variables here, hopefully the names of these will become self explanatory as the tutorial progresses.

Step 5: MovementView Constructor

In this method we accomplish the following tasks:

  • Call the super() method to give us our SurfaceView to work with.
  • Link the class up with the SurfaceHolder.Callback
  • Initialize variables regarding the circle
  • Set the speed of movement in each direction

Step 6: The onDraw Method

This is the function that will be called to draw the circle on each frame. It accomplishes two very simple tasks:

  • Repaint the Canvas all black to cover the previous frame.
  • Draw the new circle at the new set of coordinates.

Step 7: The updatePhysics Method

This function is also called every frame and accomplishes two tasks:

  • handle the simple physics of the movement
  • Update the position of the ball and make it 'bounce' if it has hit the edge

What may be confusing about this step is how the app determines which way to bounce the ball. The basic concept is that if the ball makes contact with the side, it reverses in the X direction. If the ball hits the top or bottom, it reverses in the Y direction. Also, it is important that when a collision is detected, we immediately set the ball to rest exactly on that wall, not behind it as it already might be. This prevents the ball getting stuck in a loop behind the wall.

Step 8: The surfaceCreated Method

This method is called when the workable surface area for the app is first created. You should note that it is never good practice to assume a screen size. Instead, use whatever means necessary to determine width/height information during the app runtime. This method accomplishes the following tasks:

  • Grab the rectangle bounding area of the canvas and pass the width and height to the respective variables.
  • Set the initial position of the ball to the top center of the screen.
  • Create the UpdateThread and start it.

From the point that the UpdateThread begins running, the ball will begin to move:

Step 9: The surfaceChanged Method

This method is not used in our app but is required by the SurfaceHolder.Callback implementation.

Step 10: The surfaceDestroyed Method

This method deals with exiting the app and shutting down the thread. If we tried to shut down the app without dealing with the thread, the user would see a very annoying error dialog everytime they attempt to close the app. This small piece of code will let the thread finish the current task before closing, hence eliminating the error.

Your final MovementView file should now look something like this:

Section Two: Threads

If you started off as a Flash Developer with ActionScript like I did, you probably won't be familiar with the concept of threads. Actionscript had a fantastic way of dealing with movement, but that's not how things roll in the real world. Threads can be used as Android's equivalent to OnFrameLoops, except not as easy to use. From Google's developer site:

A Thread is a concurrent unit of execution.

In plain English, this basically means threads allow multiple things to be accomplished at once in your code.

For example: you never, ever want to have your main Android class waiting for X amount of time to perform an update. Doing so will cause it to become unresponsive and the user will undoubtably become frustrated. Instead, what you do is pass the waiting on to another guy -your custom thread. He runs away happily in the background and doesn't mind waiting X amount of time. Your user is happy too, because the interface isn't dependent on when the thread finishes its work.

Step 11: The Class Outline

Let's look at the code for this thread. All steps following this will be the methods and functions that should be placed inside this class. We will also define our variables here:

Step 12: The UpdateThread Constructor

The main purpose of this constructor is to populate the surfaceHolder variable which will eventually be used to provide a reference of the Canvas.

Step 13: The setRunning Method

This method serves one simple, but essential purpose: to give the thread permission to run or not to run.

Step 14: The run Method

This is the main method of the Thread. The code in this method dictates what is done with each 'tick' of the thread. This is the list of tasks it performs:

  • Check if it has permission to run.
  • If so, check if the required time has passed to keep in line with the FPS (frames per second) value.
  • If so, set the canvas to empty.
  • Get a reference to the canvas and lock it to prepare for drawing.
  • Update the physics of the ball.
  • Draw the ball in the new position.
  • If it is safe to do so, lock and update the canvas.

Your UpdateThread file should now look like this:

And thats all the coding we need to do. If you run your app now, you should see a ball bouncing around the screen!

Conclusions

Admittedly, this has been a simplistic introduction to achieving movement in an Android application. However, I believe that once you understand the core concepts of everything in this tutorial, it makes it very easy to go on to a much more complex scenario.

For example, to make a space invaders like game, you might put all the aliens sifting side-to-side on one thread that, at a basic level, functions much like the one introduced here. Hopefully you have found this tutorial beneficial! :)

Tags:

Comments

Related Articles