Android game development (2) touch screen event processing

Source: Internet
Author: User
Tags gety

In the previous chapter, we did not remove the title bar and status bar. If the title bar and status bar are not displayed in the game, it is very easy to remove them, add the following two sentences to the onCreate method of mainActivity:
 
RequestWindowFeature (Window. FEATURE_NO_TITLE); // set no title
GetWindow (). setFlags (WindowManager. LayoutParams. FLAG_FULLSCREEN, WindowManager. LayoutParams. FLAG_FULLSCREEN); // set full screen
Hurry up and try it. To write a program, you just need to try it again ..

How can we make an image behave when the image is ready? Then human-computer interaction is required to make the game behave through the touch screen.
First, describe the coordinate system of android.
In android, the top left coordinate system is the origin coordinate (0, 0), the right is the X axis, and the down is the Y axis, which indicates that this position is because some game engines use the bottom left as the origin. Remember, if an engine is used later, there is also a concept.
Next let's take a look at how android touch screen events are handled.
First, we will analyze that the current user interface is event-driven to achieve human-computer interaction. When the screen interface receives events, it can be processed differently based on different situations to achieve human-computer interaction.
The Touch Screen events supported by android include: Press, pop-up, move, double-click, long-press, and slide.
Pressing, popping up, and moving (down, move, and up) are simple touch screen events. We will talk about this in this chapter.
Double-click, long-press, slide, and scroll must be identified based on the trajectory of the motion. There are specialized classes in Android to identify, android. view. GestureDetector. This section will be explained later.

How can this problem be achieved?
In Android, any widget or Activity inherits indirectly or directly from android. view. View. A View object can process ranging, layout, drawing, focus conversion, scroll bars, and buttons and gestures in the touch-screen area. Because our view inherits surfaceView, surfaceView inherits the view. To implement simple touch screen events, you only need to override the onTouchEvent method in the parent view class to implement simple touch screen events.

Next we will implement a function. We will use the program in the previous chapter to display the picture in the place where the touch screen is clicked and the picture can be moved according to the finger.

View Code directly
 
Package yxqz.com;

Import android. content. Context;
Import android. content. DialogInterface;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android. graphics. Canvas;
Import android. graphics. Color;
Import android. view. MotionEvent;
Import android. view. SurfaceHolder;
Import android. view. SurfaceView;
Import android. view. SurfaceHolder. Callback;

/**
* Android surfaceview touch screen event Learning
* @ Author mahaile
*
*/
Public class GameSurfaceView extends SurfaceView implements Callback {
Boolean flag; // stop refreshing the interface when the thread flag is set to false.
SurfaceHolder surfaceHolder;
GameViewThread gameViewThread;
Float x = 0, y = 0;
Int direction = 0; // The image running direction controls the Image Moving up or down
Int width, height;
Bitmap bitmap_role;
Public GameSurfaceView (Context context ){
Super (context );
SurfaceHolder = this. getHolder ();
SurfaceHolder. addCallback (this); // Add callback
Bitmap_role = BitmapFactory. decodeResource (getResources (), R. drawable. role );

// Set the focus. If the focus is not set, clicking the touch screen in this interface is invalid. The default value is false.
SetFocusable (true );
}
 
Public void onDraw (Canvas canvas ){
Canvas. drawColor (Color. BLACK );
Canvas. drawBitmap (bitmap_role, x-bitmap_role.getWidth ()/2, y-bitmap_role.getHeight ()/2, null );
}
// Override the onTouchEvent in the parent class to listen to the touch event. Remember to set the focus.
@ Override
Public boolean onTouchEvent (MotionEvent event ){
If (event. getAction () = MotionEvent. ACTION_DOWN) {// triggered when an event finger clicks the screen at the bottom of the screen.
X = event. getX ();
Y = event. getY ();
} Else if (event. getAction () = MotionEvent. ACTION_UP) {// triggered when the finger of the screen is lifted when the screen is removed

} Else if (event. getAction () = MotionEvent. ACTION_MOVE) {// triggered when the finger that handles the move event moves on the screen
X = event. getX ();
Y = event. getY ();
}
Return true; // return true to handle the move event. For details, see the description below.
 
}
 
Public void surfaceChanged (SurfaceHolder surfaceHolder, int format, int width, int height ){
}

Public void surfaceCreated (SurfaceHolder surfaceHolder ){
// Obtain the width and height of the screen. It is valid only when the surface is created. It cannot be obtained in the constructor.
Width = this. getWidth ();
Height = this. getHeight ();
// Initialize the drawing thread
GameViewThread = new GameViewThread ();
GameViewThread. flag = true;
GameViewThread. start ();
}
Public void surfaceDestroyed (SurfaceHolder surfaceHolder ){
GameViewThread. flag = false; // destroy the thread
}

Class GameViewThread extends Thread {
Public boolean flag;
Public void run (){
While (flag ){
Canvas canvas = null;
Try {
Canvas = surfaceHolder. lockCanvas (); // lock the canvas and obtain the canvas
OnDraw (canvas); // call onDraw to render to the screen
SurfaceHolder. unlockCanvasAndPost (canvas); // do not forget this step. Otherwise, the page cannot be displayed.
} Catch (Exception e ){
E. printStackTrace ();
}
Try {
Thread. sleep (10); // The Thread sleep time controls the number of frames.
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} // Refresh every 10 milliseconds
}
}
}
}
The MainActivity class will not post code here, because it is as simple as the previous chapter.

OnTouchEvent () Return Value explanation
Explanation:
OnTouchEvent (), by default, the Oeverride method is used. Normally, the system calls super. onTouchEvent () and returns the Boolean value. Note that if you call super. onTouchEvent () is likely not to do anything in super, and false is returned. Once false is returned, it is likely that the following events (such as Action_Move and Action_Up) are returned) will not receive, so in order to ensure that the event can be received after the warranty, pay attention to whether to directly call super. touchEvent ().


 
Next, let's take a look at how to use android gesture recognition.

 
Note: Do not forget setFocusableInTouchMode (true) during initialization; get focus in Touch Screen mode, which is similar to setFocusable (true );
-- SetFocusable (true); // This method is used to respond to keys! If you define a class that inherits the View, and implement the onKeyDown method again, the onKeyDown method is called only when the View gets the focus, the onKeyDown method in Actvity is called only when all controls do not process the key event.
 

Code: http://www.bkjia.com/uploadfile/2012/0417/20120417100011952.rar
 


Supplement:
In android, when we use the touch screen in the simulator, we click the simulator screen once and then release it. First, we trigger ACTION_DOWN and then ACTION_UP. If we move it on the screen, ACTION_MOVE will be triggered; this is normal, but in a real machine, is it true? The answer is no. If we test the real machine, the process is as follows:
Trigger ACTION_DOWN first. If the finger is not lifted, the ACTION_MOVE event will be triggered all the time.
There are two reasons: First, Android is very sensitive to touch screen events! Second: although our fingers are still and not moving, this is not the case! When our fingers touch the screen of the mobile phone, we feel that our fingers are still motionless. In fact, our fingers are shaking and shaking. So the action_move event will be triggered all the time.
What is the impact of this situation on our program?
 
For example, when the app thread uses 10 ms for drawing every time, when the finger touches the screen, about 10 motionevents will be generated in the short 0.1 seconds, in addition, the system will send these events to the listening thread as quickly as possible. In this case, the cpu may be busy processing the onTouchEvent event during this period, resulting in insufficient resources to process the app interface, and refresh the page with one card and one card.
In fact, we don't need to press the buttons to respond so many times. Instead, we need to accept a user touch event after each drawing or before drawing, this will prevent the frame rate from dropping too much, isn't it ?! If we can slow down the events triggered by the touch screen monitoring event, isn't it enough to solve this problem? It's just so optimized.

 
@ Override
Public boolean onTouchEvent (MotionEvent event ){
If (event. getAction () = MotionEvent. ACTION_DOWN ){
} Else if (event. getAction () = MotionEvent. ACTION_UP ){
} Else if (event. getAction () = MotionEvent. ACTION_MOVE ){
}
Synchronized (this ){
Try {
This. wait (Time); // enables the event thread to sleep to reduce the number of triggers
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
Return true;
}
 
The above code is added to your onTouch, but note that the above thread synchronization object uses this. If this class is also used as a synchronization object by another class, a deadlock may occur, if this class has been used as a synchronization object, we can use a new object as the onTouch synchronization object during reinitialization.

 
From android, unity3d

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.