Andengine Game Development Series tutorial (1)

Source: Internet
Author: User
Tags libgdx

Link: http://www.apkbus.com/android-130403-1-1.html


I. Introduction

Developed based on the libGDX framework, AndEngine uses OpenGL ES to draw images. The underlying layer is written in C ++ and implemented through JNI calls. Therefore, it is highly efficient and powerful. At the same time, it integrates the Box2D physical engine to achieve some complex physical effects. Android. Compared with the Libgdx engine, AndEngine has more game components and extensions. By default, it can support Chinese characters and screen coordinate system painting is more in line with the general Android plotting habits. Features:

① Open Source
AndEngine is an open-source project. This allows developers to find the answer directly from the source code when encountering problems, and modify and expand the AndEngine according to their own needs. The source code of AndEngine is hosted on github.
② Efficiency
AndEngine is mainly developed using the Java language, but in the case of a large amount of time-consuming functions, AndEngine uses C/C ++ local code for development. For example, physical engines or audio processing. As a user, you only need to pay attention to the Java end. It has encapsulated all the local code. Compared with other android game engines, AndEngine has obvious efficiency advantages.
③ Special Effects
AndEngine has a Particle System that can efficiently simulate flame, rain, snow, and water. It also has advanced effects such as Motion Streak (Dynamic Fuzzy) and Ratial Blur (Radial fuzzy.
④ Physical Engine
The AndEngine encapsulation of the physical engine Box2D [3] is surprising. It uses JNI to encapsulate C ++ of Box2D, which makes it run much faster than other physical engines of the same level, such as Box2D. If your game is ready to use the physical engine, consider the AndEngine first.
⑤ Extended

Andengine officially provides several extension packages. For example: andenginelivewallpaperextension dynamic wallpaper extension, andenginetexturepackerextension texture packaging extension, andenginephysicsbox2dextension physical engine extension, andenginemultiplayerextension multi-player extension, and so on. This allows developers to easily implement multiple functions.

Ii. Initial Construction

1. create a new project, create a new Lib folder in the project root directory (if there is a new folder), paste the JAR file to the Lib folder, right-click the JAR file -- Build path -- add to build path, and right-click the JAR file -- Build path -- configure build path-click andengine. select jar


2. Simple startup Screen

Here we will use andengine to draw a texture, and we need to modify the activity code.

Public class LeekaoActivity extends BaseGameActivity {// Camera size private static final int CAMERA_WIDTH = 800; private static final int CAMERA_HEIGHT = 480; Camera mCamera; // Texture private Texture mTexture; private TextureRegion mLeekaoTextureRegion; // The method in the superclass and interface is overwritten @ Overridepublic Engine onLoadEngine () {this. mCamera = new Camera (0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); // TODO Auto-generated method stubreturn new Engine (new EngineOptions (true, ScreenOrientation. LANDSCAPE, new RatioResolutionPolicy (CAMERA_WIDTH, CAMERA_HEIGHT), this. mCamera);} @ Overridepublic void onLoadResources () {// TODO Auto-generated method stubthis. mTexture = new Texture (1024,102 4, TextureOptions. BILINEAR_PREMULTIPLYALPHA); this. mLeekaoTextureRegion = TextureRegionFactory. createFromAsset (this. mTexture, this, "leekao/leekao.jpg", 0, 0); this. mEngine. getTextureManager (). loadTexture (this. mTexture) ;}@ Overridepublic Scene onLoadScene () {// TODO Auto-generated method stubthis. mEngine. registerUpdateHandler (new FPSLogger (); final Scene scene = new Scene (1); // the camera is placed in the center of the screen final int centerX = (CAMERA_WIDTH-this.mLeekaoTextureRegion.getWidth ()/2; final int centerY = (CAMERA_HEIGHT-this.mLeekaoTextureRegion.getHeight ()/2; // create a Sprite object and add final Sprite leekao = new Sprite (centerX, centerY, mLeekaoTextureRegion); Scene. getLastChild (). attachChild (leekao); return scene;} @ Overridepublic void onLoadComplete () {// TODO Auto-generated method stub}

As follows:


The effect of the above Code is to display a screen, and the code looks a lot better. Now let's take a look at the Code:

It can be found that the basegameactivity class is inherited, which completes some andengine initialization and provides related overwriting methods. (When writing code, you can right-click -- source -- override/implement mthods and select relevant methods to speed up code writing ). Then the camera angle is set.
Code override method:
[] Onloadengine () is called when the game engine is loaded by the activity. Camera and engine object are initialized here. In the engine object, I set the screen direction to landscape ). Then there is a resolutionpolicy object of ratioresolutionpolicy. the engine can scale the image in different screen sizes Based on this policy, while maintaining the original aspect ratio.
[] The onLoadResources () method is called when resources are loaded. Create a Texture object to store the TextureRegion object for image loading. As for how TextureOptions is used to render images, the following section describes how to render images. Finally, load the texture object to the TextureManage of the engine. (You have prepared images in the assets/leekao folder)
[] The onLoadScene () method is called when the engine is about to display the scene. The Frame Count counter is initialized in the code, a scenario with only one layer is created, and the camera is centered on the screen, create an genie object that indicates the startup screen and attach it to the scene.
[] The onLoadComplete () method is called when the engine Initialization is complete. Currently, operations are not performed in this phase.


Example source code free: http://download.csdn.net/detail/lan410812571/5858285


Iii. Engine object

As you can see from the previous chapter, AndEngine contains a class called Engine, which is used together with the Android runtime environment to implement the game. Engine is the core of Activity. The first thing to develop an AndEngine game is to override the onLoadEngine () method. Initialize the Engine object:

@Overridepublic Engine onLoadEngine() {this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);// TODO Auto-generated method stubreturn new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE,new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT),this.mCamera));}

Role of the Engine object:

① Initialization and continuous maintenance of OpenGL SurfaceView object, which is used to draw on the screen
② Manage user input Behaviors
③ Manage input of Various Sensors
④ Manage the text font library
⑤ Create and manage the loading and playing of music sound effects.
6. Regularly update the logic of the remaining parts of the AndEngine to drive changes in the game status.

The default constructor of the Engine is:
Public Engine (final EngineOptions pEngineOptions)

The constructor of the EngineOptions class:
Public EngineOptions (boolean pFullscreen, ScreenOrientation pScreenOrientation, IResolutionPolicy pResolutionPolicy, Camera pCamera)
The parameter passed to the new EngineOptions informs AndEngine of how to set the Engine object of the game.
① PFullscreen: whether to display in full screen;
② ScreenOrientation: optional value: LANDSCAPE (LANDSCAPE) PORTRAIT (LANDSCAPE)
③ PResolutionPolicy: tells the Engine object how to handle different device screen sizes:

RatioResourcePolcy: stretch the image as much as possible to fill the screen while keeping the aspect ratio unchanged. The above method is used.
FillResourcePolicy: Ignore the aspect ratio and fill the screen directly.
FixedResourcePolicy: Fixed aspect ratio without scaling.
RelativeResourcePolicy: scale the source image to a specified multiple.

④ PCamera: indicates the camera viewpoint used by the player to observe the scene. constructor:

Public Camera (float pX, float pY, float pWidth, float pHeight)

PX and pY indicate the origin coordinate, pWidth and pHeight indicate the length and width of the visible part of the scene, and the Unit is pixel.


Iv. Menu scenarios

AndEngine provides a menu system MenuScene, which integrates menus into the game and supports text menus and graphic menus. Menus belong to a special scenario class in AndEngine. They display an ordered list composed of text or graphics, and can be animated when a player touches them.
The MenuScene class is a subclass of Scene and has four constructors:
1) MenuScene ()
2) MenuScene (final Camera pCamer)
3) MenuScene (final IOnMenuItemClickListencer pOnMenuItemClickListencer)
4) MenuScene (final Camera pCamer, final IOnMenuItemClickListencer pOnMenuItemClickListencer)

The Canmera object that pCamer uses to display scenes
POnMenuItemClickListencer is the listener of the menu click event.

Methods related to the MenuScene class
① AddMenuItem (final IMenuItem pMeuItem)
Add menu item

② GetMenuItmCount ()
Returns the number of menu items in the menu list.

③ SetChildScene (Scene pChildScene, boolean pModalDraw, boolean pModalUpdate, boolean pModalTouch)
Attaches a scenario as a sub-scenario to the current menu scenario

Menu item type:
Textmenuitem text menu item: Constructor
Textmenuitem (int pid, font pfont, string ptext)
PID: A unique integer identifier used to identify the clicked menu in The onclick () callback method.
Pfont: font used to display menus
Ptext: displayed text

Spritemenuitem graphical menu item:

Spritemenuitem (int pid, textureregion ptextureregion)
Ptextureregion: SPRITE map used to display graphic menu items

Animatedspritmenuitem animation menu item:

Animatedspritemenuitem (final int PID, Fina tiledtextureregion ptiletextureregion)
Ptiletextureregion: displays animated sprite textures.

Colormenuitemdecorator compound color menu item:
Colormenuitemdecorator (imenuitem pmenuitem, float pselectedred, float pselectedgreen, float pselectedblue, float punselectedred, float punselectedgreen, float punselectedblue)
When you click, the color of the menu item changes. Although there are many parameters, it is actually very simple, that is, the RGB color value.
The menu item to be modified by pmenuitem.

ScaleMenuItemDecorator compound scaling menu item:
ScaleMenuItemDecorator (IMenuItem pMenuItem, float pSelectedScale, float pUnselctedScale)
Similar to the preceding method, the menu item size changes when you click.

In addition to the default Engine, AndEngine also provides other Engine classes. The following classes are subclasses of the Engine class, so they inherit the basic features.
FixedStepEngine: the fastest frame rate.
LimitedFPSEngine: run at a fixed frame rate
SingleSceneSplitScreenEngine: displays the same scenario from different viewpoints in two windows.
DoubleSceneSplitScreenEngine: different scenarios are displayed on the split screen.

Example source code free: http://download.csdn.net/detail/lan410812571/5858501

<P> public class MainMenu extends BaseGameActivity implementsIOnMenuItemClickListener {private static final int CAMERA_WIDTH = 800; private static final int CAMERA_HEIGHT = 480; // index IDprotected static final int MENU_PLAY = 0; protected static final int MENU_SCORES = MENU_PLAY + 1; protected static final int MENU_OPTIONS = MENU_SCORES + 1; protected static final int values = MENU_OPTIONS + 1; protected static final int MENU_EXIT = values + 1; protected Camera mCamera; protected Scene values; private Texture values; private TextureRegion values; private Texture mExitTexture; private TextureRegion mExitTextureRegion; protected MenuScene break; private Font mfont; protected Texture mFontTexture; @ Overridepublic Engine onLoadEngine () {// TODO Auto-generated method stubthis. mCamera = new Camera (0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine (new EngineOptions (true, ScreenOrientation. LANDSCAPE, new RatioResolutionPolicy (CAMERA_WIDTH, CAMERA_HEIGHT), this. mCamera);} @ Overridepublic void onLoadResources () {// TODO Auto-generated method stub // load font and texturethis. mFontTexture = new Texture (256,256, TextureOptions. BILINEAR_PREMULTIPLYALPHA); FontFactory. setAssetBasePath ("fonts/"); this. mfont = FontFactory. createFromAsset (this. mFontTexture, this, "JOKERMAN. TTF ", 50, true, Color. RED); this. mEngine. getTextureManager (). loadTexture (this. mFontTexture); this. mEngine. getFontManager (). loadFont (this. mfont); this. mMenuBGTexture = new Texture (2048,102 4, TextureOptions. BILINEAR_PREMULTIPLYALPHA); this. mMenuBGTextureRegion = TextureRegionFactory. createFromAsset (mMenuBGTexture, this, "menu/menu_bg.jpg", 0, 0); this. mEngine. getTextureManager (). loadTexture (mMenuBGTexture); // this. mexico Texture = new Texture (256,256, TextureOptions. BILINEAR_PREMULTIPLYALPHA); this. mexico textureregion = TextureRegionFactory. createFromAsset (mExitTexture, this, "menu/menu_exit.png", 0, 0); this. mEngine. getTextureManager (). loadTexture (Mexico texture);} protected void createStaticMenuScene () {this. mStaticMenuScene = new MenuScene (this. mCamera); final IMenuItem playMenuItem = new feature (new TextMenuItem (MENU_PLAY, mfont, "Play Game"), 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f); playMenuItem. setBlendFunction (GL10.GL _ SRC_ALPHA, GL10.GL _ ONE_MINUS_SRC_ALPHA); this. mStaticMenuScene. addMenuItem (playMenuItem); final IMenuItem scoresMenuItem = new ScaleMenuItemDecorator (new TextMenuItem (MENU_SCORES, mfont, "Scores"), 1.2f, 1.0f); scoresMenuItem. setBlendFunction (GL10.GL _ SRC_ALPHA, GL10.GL _ ONE_MINUS_SRC_ALPHA); this. mStaticMenuScene. addMenuItem (optional); final IMenuItem optionsMenuItem = new items (new Dimensions (new TextMenuItem (MENU_OPTIONS, mfont, "Options"), 1.2f, 1.0f), 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f); optionsMenuItem. setBlendFunction (GL10.GL _ SRC_ALPHA, GL10.GL _ ONE_MINUS_SRC_ALPHA); this. mStaticMenuScene. addMenuItem (optionsMenuItem); final IMenuItem aboutMenuItem = new TextMenuItem (MENU_ABOUT, mfont, "Abuot"); aboutMenuItem. setBlendFunction (GL10.GL _ SRC_ALPHA, GL10.GL _ ONE_MINUS_SRC_ALPHA); this. mStaticMenuScene. addMenuItem (aboutMenuItem); final IMenuItem exitMenuItem = new ScaleMenuItemDecorator (new SpriteMenuItem (MENU_EXIT, mExitTextureRegion), 1.2f, 1.0f); exitMenuItem. setBlendFunction (GL10.GL _ SRC_ALPHA, GL10.GL _ ONE_MINUS_SRC_ALPHA); this. mStaticMenuScene. addMenuItem (exitMenuItem); this. mStaticMenuScene. buildAnimations (); this. mStaticMenuScene. setBackgroundEnabled (false); this. mStaticMenuScene. setOnMenuItemClickListener (this) ;}@ Overridepublic Scene onLoadScene () {// TODO Auto-generated method stubthis. mEngine. registerUpdateHandler (new FPSLogger (); this. createStaticMenuScene (); final int centerX = (CAMERA_WIDTH-this. mMenuBGTextureRegion. getWidth ()/2; final int centerY = (CAMERA_HEIGHT-this. mMenuBGTextureRegion. getHeight ()/2; this. mMenuScene = new Scene (1); final Sprite menubg = new Sprite (centerX, centerY, mMenuBGTextureRegion); mMenuScene. getLastChild (). attachChild (menubg); mMenuScene. setChildScene (mStaticMenuScene); return this. mMenuScene ;}@ Overridepublic void onLoadComplete () {// TODO Auto-generated method stub} @ Overridepublic boolean encode (MenuScene pMenuScene, IMenuItem pMenuItem, float success, float success) {// TODO Auto-generated method stubswitch (pMenuItem. getID () {case MENU_PLAY: Toast. makeText (MainMenu. this, "paly selected", Toast. LENGTH_SHORT ). show (); return true; case MENU_SCORES: Toast. makeText (MainMenu. this, "scores selected", Toast. LENGTH_SHORT ). show (); return true; case MENU_OPTIONS: Toast. makeText (MainMenu. this, "options selected", Toast. LENGTH_SHORT ). show (); return true; case MENU_ABOUT: Toast. makeText (MainMenu. this, "about selected", Toast. LENGTH_SHORT ). show (); return true; default: return false ;}}}

V. Entity

In AndEngine, we can see that all game elements are sub-classes of Entity, such as Scene, Sprite, Tile, graphic Texture, particle Partical, and text are Entity objects. The Entity object can be modified using the Modifier object Modifier. AndEngine adopts the Entity/component design method in game design. This method regards all objects as Entity objects rather than designing a class for each object. Compared with the full object-oriented model, this method facilitates code management and modification.
Entity class:
Entity is a super class that includes all visible objects in the Scene class. Therefore, it also includes the public attributes of visible objects. Therefore, you can set Modifier to modify it. These attributes are:
[] Float mX, current position of mY Entity object
[] Float minitialx, initial position of the minitialy object
[] Whether the Boolean mvisible object is visible
[] Boolean mignoredupdate object update?
[] Position of the int mzindex object in the display sequence (ratio layer superposition)
[] Ientity mparent upper-level object of this object
[] Smartlist <ientity> sub-Object List of the mchildren object
[] Float mrotation object Rotation Angle
[] Scaling factor of Float mscale object
[] Float malpha object transparency
[] Updatehandlerlist mupdatehandlers applies to the updatehandler Object List of this object

Constructor and method of entity class:
Entity ()
Entity (final float PX, final float Py)

Location-related
Float getx ()/Gety () returns the X and Y coordinates of the current position.
Float getinitialx ()/getintialy () returns the initial X and Y coordinates of the entity object.
Void setposition (final float PX, final float Py) sets the location of the entity object
Setposition (final ienity potherentity) sets the location of the input entity object to the location of this entity object

Scaling Problems
Float isScaled () returns true if the scaling factor is not 1.0f
Float getScaleX () returns the horizontal scaling factor
Void setScale (final float pScaleX, fnal float pScaleY) sets the scaling factor in both directions

Color-related
In AndEnigine, the color of the Entity object is a multiplier, equivalent to overlay the color on the source image.
Float getRed ()...
Void setColor (final float pRed, final float pGreen, final float pBlue, final float pAlpha)

Rotation
Float getRotation ()
SetRotation (final float pRotation)
Get and set the rotation angle.

Manage Sub-objects
Entity objects are usually organized in layers for batch modification. If the upper-layer object is modified, the modified effect is automatically applied to all its sub-objects, but the modified effect is not passed to the upper-layer object.
IEnitity getFirstChild ()
GetLastChild ()
Obtain the first and last child objects of the Entity object.
Void attachChild (final IEntity pEntity)
Add the new object to this entity object as the last child object.
Ientity getchild (final int index)
Returns the child object of the cshu location.
Int getchildcount ()
Obtain the number of sub-objects.

The length is too long and loading is too slow.

Address: http://blog.csdn.net/lan410812571/article/details/9717561

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.