Deep analysis of the spritebatch of LIBGDX

Source: Internet
Author: User
Tags libgdx

LIBGDX Sharing Resources

Because the LIBGDX can run on multiple platforms, the theoretical resources should be placed in the core directory because both Android and desktop editions contain the home directory. But Android has strict rules on how to store these files, and we have to put resources in a fixed directory. So if you create a project that needs to run under an Android device, you must put the resources in the resource directory that the Android project automatically creates . If only practice can be placed under the core project.

The use of a spritebatch


From the above you can see that spritebatch inherits in disposable, so at the end of the game you must call the Dispose method to free up memory.
SpriteBatch uses screen coordinates (the contents of a section can be used for coordinates), the origin is in the lower left corner of the screen, the x-axis to the right, and the y-axis upward. Origin is also in the lower left corner of the screen.

All drawing commands of the Batch operate on screen coordinates. The screen coordinate system has a x-axis pointing to the right, an y-axis pointing upwards and the origin are in the Lowe R left corner of the screen

The code can specify that SpriteBatch can draw up to 5,460 objects, or the program throws an exception

32767 is Max index, so 32767/6-(32767/6 3) = 5460.
if (Size > 5460) throw new IllegalArgumentException ("Can ' t has more than 5460 sprites per batch:" + size);

SpriteBatch and stage can draw image resources on the screen from the current knowledge, but there are other methods such as box2d, but that is far from the tutorial. since SpriteBatch is a very memory-intensive object, it is recommended that there be only one in the entire game, and call the Dispose method at the end of the game

To draw an object, first call the begin () method to tell Libgdx to prepare the drawing, and draw the end to call the end () method to tell Libgdx to finish the drawing and prepare for the finishing work. This process is to draw the object to be drawn together in the cache, or you can first call flush () to draw the object in advance

/** Draws a rectangle with  theBottom left corner atX, Y have the givenWidth andHeightinchPixels. The rectangle is Offset  by* Originx, Originy relative to  theOrigin. SCALE Specifies theScaling factor bywhich theRectangle should be scaledaround* Originx, Originy. Rotation Specifies theAngle ofCounter clockwise rotation of  theRectanglearoundOriginx, Originy. The * portion of  the{@link Texture}given  bySRCX, Srcy andSrcwidth, Srcheight isUsed. These coordinates andSizes isgiven inch* Texels. FlipX andFlipY Specify whether theTexture portion should be flipped horizontallyorVertically. * @param x theX-coordinateinchScreenSpace* @param y theY-coordinateinchScreenSpace* @param Originx theX-coordinate of  theScaling andRotation origin Relative to  theScreenSpaceCoordinates * @param originy theY-coordinate of  theScaling andRotation origin Relative to  theScreenSpaceCoordinates * @param width theWidthinchpixels * @param Height theHeightinchpixels * @param ScaleX theScale of  theRectanglearoundOriginx/originyinchX * @param ScaleY theScale of  theRectanglearoundOriginx/originyinchY * @param rotation theAngle ofCounter clockwise rotation of  theRectanglearoundOriginx/originy * @param SRCX theX-coordinateinchTexelSpace* @param Srcy theY-coordinateinchTexelSpace* @param srcwidth theSource with inchTexels * @param srcheight theSOURCE HeightinchTexels * @param flipx whether toFlip theSprite Horizontally * @param flipy whether toFlip theSprite vertically */public void Draw (Texture Texture, float x, float y, float originx, float originy, float width, FL Oat height, float scaleX, float scaleY, float rotation, int srcx, int srcy, int srcwidth, int srcheight,BooleanFLIPX,BooleanFLIPY);

Above is the spritebatch to draw texture the most complete method, understand this method, the rest of the method is easy to understand. The currently created App Default window is 640*480,
Public lwjglapplication (Applicationlistener listener) {This (listener, NULL, 640, 480), or it can be modified by config itself. The following code comment has a detailed explanation

    Private StaticFinal String TAG = SpriteBatchTest1.class. Getsimplename ();    SpriteBatch Batch; Texture img;intwidth, height;intScreenWidth, ScreenHeight;floatAngle =10f; @Override Public voidCreate () {batch =NewSpriteBatch (); IMG =NewTexture ("Badlogic.jpg");//Picture resource sizewidth = Img.getwidth ();        Height = img.getheight (); Gdx.app.Log(TAG,"Texture widht="+ width +"height="+height);        ScreenWidth = Gdx.graphics.getWidth ();        ScreenHeight = Gdx.graphics.getHeight (); Gdx.app.Log(TAG,"Screen width="+ ScreenWidth +"height="+ Gdx.graphics.getHeight ()); } @Override Public voidRender () {Gdx.gl.glClearColor (1,0,0,1);        Gdx.gl.glClear (Gl20.gl_color_buffer_bit); Angle = (angle +2) % the; Batch.begin ();//Draw a picture with the default texture size//Batch.draw (IMG, 0, 0);        //This effect is the same as the above effectBatch.draw (IMG,0,0, Width *0.5f, Height *0.5f, width, height,1.0f,1.0f,0.0f,0,0, width, height,false,false);//From the center of the screen, the image is drawn in half of the texture, which equates to half the image reductionBatch.draw (IMG, screenwidth *0.5f, ScreenHeight *0.5f, Width *0.5f, Height *0.5f);//at (350,0) This position is in texture size, but only the texture is drawn 100*100Batch.draw (IMG, -,0, Width *0.5f, Height *0.5f, width, height,1.0f,1.0f,0.0f,0,0, -, -,false,false);//In (0,300) This position draws a picture at the size of 100*100, while the origin size is also changed to 100*0.5, while the picture rotates at a fixed speedBatch.draw (IMG,0, -, -*0.5f, -*0.5f, -, -,1.0f,1.0f, Angle,0,0, width, height,false,false);    Batch.end (); } @Override Public voidDispose () {//Unused resources to be destroyed, their common things implements disposableBatch.dispose ();    Img.dispose (); }

The remaining code can be self-filled, the final effect such as:

The use of SpriteBatch two

In our reference to other people's code is often seen, in the process of using the camera in combination with viewport, because in the real world we use a kilometer kg, so need a conversion, if I run 10KM per hour, conversion is 2.77777778 per second (10 * 1000/3600). The following code is a brief introduction to the process

Private StaticFinal String TAG = SpriteBatchTest2.class. Getsimplename ();Private StaticFinalfloatWorld_to_screen =1.0f/100.0f;Private StaticFinalfloatScene_width =12.80f;Private StaticFinalfloatScene_height =7.20f;    SpriteBatch Batch;    Texture img;    Viewport Viewport; Orthographiccamera camera;intWidthintHeightfloatOriginx;floatOriginy;floatAngle =10f; @Override Public voidCreate () {Gdx.app.Log(TAG,"Create"); Batch =NewSpriteBatch (); IMG =NewTexture ("Badlogic.jpg"); Camera =NewOrthographiccamera (); Camera.position.Set(Scene_width/2f, Scene_height/2f,0.0f);        Camera.update (); Gdx.app.Log(TAG,"camera.x"+ camera.position.x);//viewport = new Fitviewport (scene_width, scene_height, camera);        //To facilitate the observation of the effect, convert Fitviewport to StretchviewportViewport =NewStretchviewport (Scene_width, scene_height, camera);        width = Img.getwidth ();        Height = img.getheight (); Originx = width *0.5f; Originy = Height *0.5f; Gdx.app.Log(TAG,"Width="+ width +"height="+height); } @Override Public voidRender () {Gdx.gl.glClearColor (1,0,0,1);        Gdx.gl.glClear (Gl20.gl_color_buffer_bit); Angle = (angle +2) % the;        Batch.setprojectionmatrix (camera.combined); Batch.begin ();//Batch.draw (IMG, 0, 0, Width * world_to_screen, Height * world_to_screen);        //The above and below statements have the same effectBatch.draw (IMG,0,0, Originx * world_to_screen, Originy * world_to_screen, Width * world_to_screen, Height * world_to_screen ,1.0f,1.0f,0.0f,0,0, width, height,false,false);//Batch.draw (IMG, 6.4f, 3.6f, Width * world_to_screen, Height * world_to_screen);        //above and below the statement is the same but added an angle to rotate the picture, want to effect the same origin also need *world_to_screen, but rotate at a fixed angleBatch.draw (IMG,6.4f,3.6f, Originx * world_to_screen, Originy * world_to_screen, Width * world_to_screen, Height * world_to_screen ,1.0f,1.0f, Angle,0,0, width, height,false,false); Batch.draw (IMG,0.0f,7.2f-Height * world_to_screen, Width * world_to_screen, Height * world_to_screen);    Batch.end (); } @Override Public voidResizeintWidthintHeight) {viewport.update (width, height); Gdx.app.Log(TAG,"Resize"); } @Override Public voidPause () {Gdx.app.Log(TAG,"Pause"); } @Override Public voidResume () {Gdx.app.Log(TAG,"Resume"); } @Override Public voidDispose () {img.dispose ();        Batch.dispose (); Gdx.app.Log(TAG,"Dispose"); }

The first is a camera is to use orthogonal projection to watch our game world, in order to facilitate the drawing, to make a move, at the beginning of the coordinates such as

But the method is converted so that the camera's projection is exactly the same as screen view
Camera.position.set (scene_width/2f, scene_height/2f, 0.0f);
Camera.update ();
The results of the final program run as

Deep analysis of the spritebatch of LIBGDX

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.