Android game programming (version 2) from scratch Chapter 4 responding to user events

Source: Internet
Author: User
Chapter 4 responding to user events

The previous chapter describes how to display text and images. In general, the next step is about animation. However, as we mentioned earlier, using view is not the final choice. It requires a lot of complicated code to implement animation. Relatively speaking, it is easier to learn how to respond to user events.

The first half of this chapter explains the response to the key event, but this is not the final solution, because the mobile phone may not have a hard keyboard, and you need to use a virtual keyboard, therefore, we will explain the design and implementation of the virtual keyboard in the second part.

Similar to plotting, view responds to user events through callback functions. There are multiple keyboard Event Callback functions, which correspond to different events. Currently, we only use onkeydown for the event where the buttons are pressed. Other functions will be used later. Let's reload onkeydown (the method for reloading a function is described in the previous chapter ):

@ Override

Public BooleanOnkeydown (IntKeycode, keyevent event ){

//TodoAuto-generated method stub

Return Super. Onkeydown (keycode, event );

}

Onkeydown has two parameters: keycode and event. The keycode can be used to determine which key is pressed. The event is complicated and contains more information about the key.

Now we need to press the key to control the protagonist's movement in four directions. The so-called movement means to display the protagonist's image at different positions, that is, to change the second and third parameters in the drawbitmap function. For example, if you press the right arrow key, we will increase the x-axis so that the next time it is displayed, the main character will go to the right. To save time, we should take the figure "battlecity" as the main character. First define two global variables X and Y, then change the values of x and y in onkeydown, and then redraw the view. Because the Code has no difficulty, I will not explain it.

Public ClassGameviewExtendsView {

IntX = 0, y = 0;

......

@ Override

Protected VoidOndraw (canvas ){

......

Canvas. drawbitmap (BMP, x, y,NewPaint ());

}

@ Override

Public BooleanOnkeydown (IntKeycode, keyevent event ){

//TodoAuto-generated method stub

Switch(Keycode ){

CaseKeyevent.Keycode_dpad_up:

Y-= 10;

Break;

CaseKeyevent.Keycode_dpad_down:

Y + = 10;

Break;

CaseKeyevent.Keycode_dpad_left:

X-= 10;

Break;

CaseKeyevent.Keycode_dpad_right:

X + = 10;

Break;

}

Postinvalidate (); // notification system re-Painting View

Return Super. Onkeydown (keycode, event );

}

}

After that, we would like to test it, but now you will find that the buttons do not respond at all. This is a special point. When the view is displayed, the focus is not obtained by default. That is to say, the key action is not sent to the view, so you need to add a sentence in the constructor.

PublicGameview (context ){

......

Setfocusable (True);

}

Run the program again to see if the picture is moving according to our instructions.

As mentioned above, many mobile phones do not have a hard keyboard, so we need a soft keyboard solution. A soft keyboard displays a keyboard on the screen, and then responds to the user's touch screen operation, simulating a keyboard operation. For the tank wars, we only need to display a simulated game handle on the screen (you have not forgotten the image display method. You can adjust the display position according to the simulator ):

Perform operations when you touch the direction keys and enable keys on the simulated handle. Let's take the arrow keys for demonstration. The steps are as follows: First, determine the area (red box) of the four arrow keys on the screen ), then, in the response function of the touch screen event, determine whether the event occurs in the direction key area. Finally, if the event occurs in the area, perform the corresponding operation.

Next, we introduce a very useful class rect (rectf and rect are basically the same, but float is used as the coordinate parameter). rect is short for Rectangle. As the name suggests, this class represents a rectangle. Rect defines the range of the rectangle by four sides of the rectangle. They are left, right, top, bottom, and ,:

Convert to screen coordinates, top is the vertical coordinate of the rectangle sitting, left is the horizontal coordinate of the rectangle sitting, right is the horizontal coordinate of the bottom right corner of the rectangle, buttom is the vertical coordinate of the bottom right corner. With rect, we can easily represent the locations of each key of the virtual handle. At the same time, rect also provides some useful functions, in which rect. Contains (x, y) can determine whether the vertex (X, Y) is in the rectangle frame, which is exactly what we need.

Now we can start coding. First, create a rect for the direction keys of the virtual keyboard (you can use a drawing tool to measure coordinates ):

Rect rkeyup =NewRect (56,290, 86,320 );

Rect rkeydown =NewRect (56,350, 86,380 );

Rect rkeyleft =NewRect (26,320, 56,350 );

Rect rkeyright =NewRect (86,320,116,350 );

Then reload the touch screen response function:

@ Override

Public BooleanOntouchevent (motionevent arg0 ){

//TodoAuto-generated method stub

Return Super. Ontouchevent (arg0 );

}

Next, we need to determine whether the touch screen operation is pressed. If so, obtain the coordinates (x, y), then judge the buttons where the coordinates are located, and perform the corresponding operations.

@ Override

Public BooleanOntouchevent (motionevent arg0 ){

//TodoAuto-generated method stub

If(Arg0.getaction () = motionevent.Action_down){

IntAx = (Int) Arg0.getx ();

IntAy = (Int) Arg0.gety ();

If(Rkeyup. Contains (ax, ay )){

Y-= 10;

}Else If(Rkeydown. Contains (ax, ay )){

Y + = 10;

}Else If(Rkeyleft. Contains (ax, ay )){

X-= 10;

}Else If(Rkeyright. Contains (ax, ay )){

X + = 10;

}

Postinvalidate (); // do not forget to refresh the screen

}

Return Super. Ontouchevent (arg0 );

}

Now let's run it. Every time you click the arrow key of the simulated handle, the picture will move

So far, we have introduced two methods to respond to user events. However, to truly control a game, more work is required, which will be explained in detail later.

Related Article

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.