Libgdx example-superjumper Analysis 2. Interface and touch screen events

Source: Internet
Author: User
Tags gety libgdx

The previous section shows that mainmenuscreen is the main menu class, that is, the first screen displayed after the game starts. First, let's look at the main menu interface, as shown below:

The mainmenuscreen class is analyzed as follows:

public class MainMenuScreen extends Screen {    OrthographicCamera guiCam;    SpriteBatch batcher;    Rectangle soundBounds;    Rectangle playBounds;    Rectangle highscoresBounds;    Rectangle helpBounds;    Vector3 touchPoint;    public MainMenuScreen (Game game) {        super(game);        guiCam = new OrthographicCamera(320, 480);        guiCam.position.set(320 / 2, 480 / 2, 0);        batcher = new SpriteBatch();        soundBounds = new Rectangle(0, 0, 64, 64);        playBounds = new Rectangle(160 - 150, 200 + 18, 300, 36);        highscoresBounds = new Rectangle(160 - 150, 200 - 18, 300, 36);        helpBounds = new Rectangle(160 - 150, 200 - 18 - 36, 300, 36);        touchPoint = new Vector3();    }    @Override public void update (float deltaTime) {        if (Gdx.input.justTouched()) {            guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));            if (OverlapTester.pointInRectangle(playBounds, touchPoint.x, touchPoint.y)) {                Assets.playSound(Assets.clickSound);                game.setScreen(new GameScreen(game));                return;            }            if (OverlapTester.pointInRectangle(highscoresBounds, touchPoint.x, touchPoint.y)) {                Assets.playSound(Assets.clickSound);                game.setScreen(new HighscoresScreen(game));                return;            }            if (OverlapTester.pointInRectangle(helpBounds, touchPoint.x, touchPoint.y)) {                Assets.playSound(Assets.clickSound);                game.setScreen(new HelpScreen(game));                return;            }            if (OverlapTester.pointInRectangle(soundBounds, touchPoint.x, touchPoint.y)) {                Assets.playSound(Assets.clickSound);                Settings.soundEnabled = !Settings.soundEnabled;                if (Settings.soundEnabled)                    Assets.music.play();                else                    Assets.music.pause();            }        }    }    @Override public void present (float deltaTime) {        GLCommon gl = Gdx.gl;        gl.glClearColor(1, 0, 0, 1);        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);        guiCam.update();        batcher.setProjectionMatrix(guiCam.combined);        batcher.disableBlending();        batcher.begin();        batcher.draw(Assets.backgroundRegion, 0, 0, 320, 480);        batcher.end();        batcher.enableBlending();        batcher.begin();        batcher.draw(Assets.logo, 160 - 274 / 2, 480 - 10 - 142, 274, 142);        batcher.draw(Assets.mainMenu, 10, (int)(200 - 110 / 2), 300, 110);        batcher.draw(Settings.soundEnabled ? Assets.soundOn : Assets.soundOff, 0, 0, 64, 64);        batcher.end();    }    @Override public void pause () {    Settings.save();    }    @Override public void resume () {    }    @Override public void dispose () {    }}

Note:

1. First, an orthographiccamera (orthogonal camera) is initialized in the constructor, and the width and height are set to 320*480, that is, the screen size. Then set the orthographiccamera position, that is, the position point on the screen (because it is a 2D game, the Z axis is not required ). Then there is a spritebatch used to draw game images. Then there is a series of rectangle (rectangles), which are defined by (X, Y, width, height) to determine whether the corresponding options are selected in a touch screen event. Finally, it is a vector3 variable named touchpoint. This is a point class that contains coordinates of X, Y, and Z in space. It is used to record coordinates of the midpoint of a touch screen event.

2. After the constructor is executed, the update () method is called before present (). The updata () method switches and updates the Screen Based on the touch screen event, while the present () method draws the screen image. Why are these two methods called? Because mainmenuscreen exists as a member variable of the game class, the real rendering method is the render () method that implements the applicationlistener interface in the game class, it specifies that the real drawing method is to call the update and present methods of screen, and the passed parameter GDX. graphics. getdeltatime ()
Is a float parameter, which indicates the time interval of each painting, that is, the refresh time. The Code is as follows:
@Override public void render () {    screen.update(Gdx.graphics.getDeltaTime());    screen.present(Gdx.graphics.getDeltaTime());}
Note: In the actual libgdx class library, the screen interface does not have the updata and present methods. There is only one render (float time) method left and the render method in the game abstract class, it only calls the render method of the member variable screen. This means that when defining a screen of your own, you should put the drawing logic in the render method. For touch screen and button monitoring, you can use either the libgdx input class or the android API to check the specific selection conditions (note that, the coordinate system used by libgdx is different from that used by Android ).

3. Let's talk about the present () method first. The code of the present () method is similar to the Code in the previous example. It is nothing more than clearing the screen and drawing the game screen. There are several notes:

Glcommon GL = GDX. GL;

Glcommon is a public interface of gl10, gl11, and gl20. It contains all public methods. That is to say, you do not need to distinguish gl10, gl11, and gl20 to call methods in glcommon.

Guict. Update ();

Batcher. setprojectionmatrix (guict. Combined );

Since orthographiccamera is customized, the projection matrix of orthographiccamera must be passed to the batcher. In this example, guict. Combined is a member variable of the matrix4 type in the camer (orthographiccamera's parent class) class. matrix4 represents a level 4 matrix, where the projection matrix is used.
Batcher. disableblending (); batcher. Begin (); batcher. Draw (assets. backgroundregion, 0, 0,320,480); batcher. End (); batcher. enableblending ();

This is to draw a background image. As mentioned in the introduction, when you draw a large image, you should first disableblending (disable mixing) enableblending (enable hybrid) after painting ). Others are the image resources corresponding to the assets, which are relatively simple.

4. the next step is the update () method: If (GDX. input. justtouched () {guict. unproject (touchpoint. set (GDX. input. getx (), GDX. input. gety (), 0 ));

First, determine whether a new touch screen event occurs. Then, obtain the x y coordinate of the touch point and set it to the touchpoint. Then, call the guict. unproject Method for reverse projection. (This step does not understand what is the use of reverse projection ·····)

If (overlaptester. pointinrectangle (playbounds, touchpoint. x, touchpoint. y) {assets. playsound (assets. clicksound); game. setscreen (New gamescreen (game); return ;}

After obtaining the position of the touch point, you must determine which option to touch. Here, the author defines a class named overlaptester, which contains three static methods to determine whether the vertex is inside the rectangle and whether the rectangle and the rectangle are intersecting. Compare the size of the rectangle position with the position of the vertex to determine which item is clicked. For example, after clicking the play item, play the sound and switch screnn to gamescrenn ). NOTE: For the switching screen, the game here is set in the screen class member variable, while in the actual libgdx class library, screen is made into an interface. That is to say, you should place the reference of the corresponding game class in the implementation class of the specific screen interface, and call the setscreen method of the game class to switch the game screen.

Similarly, for helpscreen, and highscoresscreen, the implementation principle is the same.Note: You can define a parent screen class for all screens to directly implement the screen interface, encapsulate the same variables and methods, and inherit the parent screen from all sub-screens.
Speaking of highscoresscreen, we must mention the processing of characters in libgdx. In libgdx, all characters are actually an image, or a part of an image. Libgdx provides a bitmapfont class to process text rendering. When constructing bitmapfont, A fnt file consisting of the description text is required, and a PNG image file that provides the text. badlogic. GDX. the utils package provides built-in font. Currently, only English letters, numbers, and common symbols are supported. With spritebatch, you can complete some basic text painting. For example, during game initialization, the assets class has constructed a font variable of the bitmapfont type. The Code is as follows: public static bitmapfont font; font = new bitmapfont (GDX. files. internal ("Data/font. fnt "), GDX. files. internal ("Data/font.png"), false );

The data/font. fnt file is the construction file, and the data/font.png file is the specific character image. The default value of the third parameter is false. Both files can be generated using tools. A very powerful tool is recommended here:
Http://www.ogre3d.org/forums/viewtopic.php? F = 11 & t = 47802

Image: (the same background color was added later)

It can be seen that each character is actually a small area in the image. bitmapfont is used to split .png files into small image area Blocks Based on the. fnt file.

By calling the bitmapfont. Draw (spritbatch, charsequence, x, y) method, you can draw specific characters at a specified position. For example, to draw the top five scores in highscoresscreen, the Code is as follows:
Float y = 230; For (INT I = 4; I> = 0; I --) {assets. font. draw (batcher, highscores [I], xoffset, Y); y + = assets. font. getlineheight (); // line feed}
Bitmapfont also provides some methods to obtain the width and height occupied by a given string. For example, calculate the X coordinate of the highest score using highscoresscreen. The Code is as follows:
For (INT I = 0; I <5; I ++) {highscores [I] = (I + 1) + ". "+ settings. highscores [I]; xoffset = math. max (assets. font. getbounds (highscores [I]). width, xoffset);} xoffset = 160-xoffset/2 + assets. font. getspacewidth ()/2; // calculates the X coordinate of the center display.
Add the number of scores read in the setting class, and then call assets. font. getbounds (charsequence) returns the textbounds class of the specified string, while the textbounds class is an internal class of bitmapfont, which contains the width and height occupied by the specified string. By comparing the width of the string formed by the five highest scores, we can calculate the X coordinates of all the scores displayed in the center. The final result is as follows:

Finally, let's take a look at helpscreen, as shown below:

After comparison, we can find that the orientation of the lower part of the screen is changed, but it is the time to observe the image resources of the game. In items.png, there is only one left arrow, and there is no right arrow. In fact, the two arrows are the same image, but the parameters are different during painting, which leads to the opposite direction. below is the code for drawing arrows in the helpscreen class:
    batcher.begin();              batcher.draw(Assets.arrow, 320, 0, -64, 64);    batcher.end();
Set the start point of the painting to (, 0), that is, the bottom right of the screen, the height to 64pix, and the width to-64 pix. This achieves the drawing of Arrow reversing. You can use this technique to deal with different requirements of the same clip image. Transferred from:

Http://tonmly.blog.163.com/blog/static/174712856201162845421796/

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.