After running into issues correctly loading managed Textures in my current LibGDX project when the Android app is backgrounded and foregrounded I refactored the project to use the TextureAtlas class and TextureRegions loaded from it. The transition was surprisingly smooth: the same amount of control with drawing is available on a TextureRegion as on a Sprite. Rotation around an origin and color tinting being my primary concerns. The main difference I found between the two approaches is that drawing happens through the SpriteBatch with a passed in TextureRegion rather than drawing through the Sprite with the SpriteBatch provied as a parameter. All of the transformations that I had been applying to the Sprite are now applied through the SpriteBatch draw method instead.

As an example of this different approach here is the code for my HealthBar class's render() function before and after the refactor. 


       public void render(SpriteBatch spriteBatch){

                backgroundSprite.setBounds(viewBounds.x, viewBounds.y, viewBounds.width, viewBounds.height);

                backgroundSprite.setOrigin(viewBounds.width/2f, viewBounds.height/2f);



                barSprite.setBounds(currentHealthBounds.x, currentHealthBounds.y, currentHealthBounds.width, currentHealthBounds.height);

                barSprite.setRegionWidth((int)(barTexture.getWidth() * (currentHealth/maxHealth)));

                barSprite.setOrigin(viewBounds.width/2f-viewPadding, viewBounds.height/2f-viewPadding);





        public void render(SpriteBatch spriteBatch){                float x = viewBounds.x;                float y = viewBounds.y;                float width = viewBounds.width;                float height = viewBounds.height;                float originX = viewBounds.width/2f;                float originY = viewBounds.height/2f;                                spriteBatch.draw(backgroundRegion, x, y, originX, originY, width, height, 1, 1, rotation);
                x = currentHealthBounds.x;                y = currentHealthBounds.y;                width = currentHealthBounds.width;                height = currentHealthBounds.height;                barRegion.setRegionWidth((int)(barRegion.getTexture().getWidth() * (currentHealth/maxHealth)));                originX = viewBounds.width/2f-viewPadding;                originY = viewBounds.height/2f-viewPadding;
                spriteBatch.draw(barRegion, x, y, originX, originY, width, height, 1, 1, rotation);        }

Post Comment

Hello World!