Skip to content

Getting Started: Touch Events

September 14, 2011

Okay, so you have the framework of your game built, and you have your sprites floating around, let’s make them do things!  With most Android phones, there are two major ways of performing input: touch and accelerometer.  These are the two input methods that are most common for AndEngine games, and both can be very beneficial to a great game!  In this guide, we’re going to be taking a look at how to deal with touch events.

Scene Touch Events

Let’s start with scene touch events.  Fortunately, AndEngine has some quite useful tools that help us handle our touch events, so most of your work is done for you.  In my experience, there are really two main ways of dealing with touch: working with touch on the entire scene and working with touch on a single object.  An example of code that you would want to work with the entire scene would be my game, Rhythm Battle- the ship moves to wherever you touch on the screen.  An example of when you would prefer touch with a single object would be the game Math Monkey, where the user taps moving objects in a specific order to win.  Let’s begin with some sample code for working with touch on a scene- this code would be placed in the base of a class.

    public boolean onTouchEvent(MotionEvent event) {
        int myEventAction = event.getAction(); 

        float X = event.getX();
	float Y = event.getY();

        switch (myEventAction) {
           case MotionEvent.ACTION_DOWN:
        	break;
           case MotionEvent.ACTION_MOVE: {
            	mySprite.setPosition(X, Y);
            	break;}
           case MotionEvent.ACTION_UP:
                break;
        }
        return true;
    }

Here is what is happening in this code: onTouchEvent(MotionEvent event) is called when the user touches the screen.  The location of the user’s touch is given the name MotionEvent event (though, of course, you could name it whatever you wanted).

Now, the first thing we want to do is figure out what has been done by the user- a touch, a movement, or lifting a finger.  We do this with the command event.getAction(), which returns an event (in this case, myEventAction).  In this example, I’m using a switch to determine exactly what kind of action was.  There are a number of different touch event actions, but I’ve found the three most useful ones to be:

MotionEvent.ACTION_DOWN-  this code runs when the user first touches their finger down on the screen.

MotionEvent.ACTION_MOVE- this code will run whenever the finger is moved along the screen- such as to drag a character or item from one place to the other.

MotionEvent.ACTION_UP- you guessed it- this code runs when the user lifts their finger from the screen.

It is worth noting that in most cases, it is seen as a best practice to have buttons activate on the ACTION_UP command, rather than the ACTION_DOWN.

Another thing you’ll often need to know in game programming is exactly where the user touched the screen.  If, for example, you have a character that jumps to wherever the user touched the screen, the way you would determine where the touch was located is through the event.getX() and event.getY() commands.  These return an X or Y coordinate as an int.  (NOTE: sometimes the location on the screen doesn’t exactly correspond to the touch event due to the way AndEngine resizes the scene to fit the size of the phone- usually some basic addition or multiplication will place your sprite in the proper location)   You can then do whatever you would like with these coordinates- such as in this example, where we proceed to set the x,y position of sprite to that of the touch event. A final note- You may notice at the end that we return true; this tells the Android that the touch command has been processed.  Therefore, if this code runs, returning true, the Android will not look for any other code that the touch action may run (for example, if there is something underneath the scene).   This can be useful if you have stacked items but only want the touch action to effect the item on top of the stack, or if you want the background to react to a touch but not interfere with the game.

Item Touch Events

The other type of touch event is a TouchListener set on an individual item- such as a sprite.  When you declare the sprite (usually in onLoadScene), do so like this:

		final AnimatedSprite mySprite = new AnimatedSprite(100, 220, this.mySpriteTextureRegion) {
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
		                int eventaction = event.getAction(); 

		                float X = event.getX();
		                float Y = event.getY();

		                switch (eventaction) {
		                   case TouchEvent.ACTION_DOWN:
		        		break;
		                   case TouchEvent.ACTION_MOVE: {
		            	        this.setPosition(X, Y);
		            	        break;}
		                   case TouchEvent.ACTION_UP:
		                        break;
		                }
				return true;
			}
		};

And there is one more extremely important part:  Near the end of your OnLoadScene, there are two lines of code that are necessary in order to register with the scene that touches will be recieved: scene.registerTouchArea, and scene.setTouchAreaBindingEnabled.  Here’s what it should look like in your code:
scene.registerTouchArea(mySprite);
scene.registerTouchArea(mySecondSprite);
scene.setTouchAreaBindingEnabled(true);

I made up a second sprite (mySecondSprite- original, I know) in order to show you that though each sprite needs to registerTouchArea, setTouchAreaBindingEnabled only needs to be set to true once. 

These two lines of code are simple:

The first, registerTouchArea, tells the scene that this sprite needs to accept touch input.

The second, setTouchAreaBindingEnabled(true), tells the scene that when the user touches an object, that should be the object that the touch deals with-  even if the user drags their finger away.  For example, if you had a sprite that moved when dragged (as is the case in the above example), but you moved it under another sprite, if setTouchAreaBindingEnabled was set to false, the touch would shift to the other sprite instead.  With it set to true, the first sprite would remain touched.  While a few apps may want to have this set to false- such as an AndEngine piano- most will likely need it to be set as true.   

As you can see, beyond a few simple differences, the way a Sprite Touch Event works is a lot like the way a Scene Touch Event works.  Even the way the TouchEvent is handled is the same; the only difference is that a sprite touch event is defined when the sprite is created, and its touch area needs to be registered.  

Order of Call

So, you may be wondering- what happens if two items with touch enabled are touched at the same time?  The answer is simple: it depends on which is registered as a touch area first.  If, for example, you register a picture of a banana first and helicopter second, and then you throw the banana at the helicopter, the banana would register the touch first.  If the banana returned true, the touch event would then end.  If the banana returned false, however, the helicopter would then receive the touch.  If both returned false, then the scene would receive the touch event- in my experience, it always goes last.  However, if either the banana or the helicopter returned true, the scene would not receive the event.

Touch events are an important part of most games- with a mastery of this skill, you have another tool under your belt for making a great AndEngine game!

Up next: Getting Started: Accelerometer Events

About these ads
9 Comments
  1. Narinder Bansal permalink

    Hi will
    Your tutorials are great. Please do some tutorials on Box2D & physics based games in And Engine.
    Thanks
    Narinder Bansal
    AndEngine id: go4nishu

  2. Hello,
    I have problem with touch events – maybe can you help me? Please read my topic: http://www.andengine.org/forums/development/motionevents-doesn-t-works-properly-t5053.html

    Big thanks!

  3. yjw permalink

    Hi. This is a wonderful blog in the way you are putting together information that are kinda spread all over the place in AndEngine forums.

    I was wondering if you will be doing a piece on how touch events can work for games when paused, specifically how we can implement an on-screen pause button and the possible impact of such an implementation on animations/EntityModifiers in the scene?

    • I’m glad you’re enjoying it, yjw! I’m hoping that by putting things together like this, AndEngine will become a lot more approachable for new programmers (making the guides I wish I had when I got started!). Touch events when games are paused is definitely something within the scope of the blog in the future, but it would be too complicated for the getting started guides. I’ll put together something soon on menus, though, and I’ll see if I can fit some information in on it there! Thanks for the input!

      • yjw permalink

        Oh yes you are right. In my joy at discovering this blog it actually slipped my mind this is the “Getting Started” series! Keep up the good work!

  4. Anuj sharma permalink

    hi !…. its great, can u guide me how to go from one scene(Activity) to another in AndEngine, as in android we use intent, what to use in Andengine….?

    • Fortunately, since AndEngine is simply an extension of Dalvik (the language Android uses), any android code you would use in a normal application will also work with AndEngine- so working with intents and activities can be done exactly the same as it does with a normal Android application.

  5. Jared permalink

    Just curious, but why no mention of isActionOutside() or isActionCancelled? These are two AndEngine functions I was really hoping to see an explanation of. I can never seem to get them to fire, although I bet they are exactly what I need to solve a problem I’m having.

    http://www.andengine.org/forums/gles2/onareatouched-press-and-held-down-not-working-t7131.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 42 other followers

%d bloggers like this: