Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (109)
games submitted by our members
Games in WIP (537)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  [Android - LibGDX] Adding/Removing group from a stage is causing stutter lag?  (Read 4629 times)
0 Members and 1 Guest are viewing this topic.
Offline Shane75776
« Posted 2013-11-13 09:30:52 »

Alright so I am currently working on an my first android game. In this game there are "Balloons" that the player can run into (2d game) to increase his score. Right now the game uses many other objects and particle effects and runs perfectly smooth. I even spawn random balloons (they come up the screen randomly) without issue.

I built a "Balloon Pattern" class which basically puts balloons into a Group and adds that group to the stage. These balloons come up the screen in a pattern rather than randomly (heart, arrow, line, etc). For whatever reason, whenever a new pattern is created the game stutter lags (tiny lag spike) as the pattern is being created. I am pooling my objects so there is minimum object creation, I tested my game on a very old android phone and it ran just as well as on my Nexus 4 (the same lag spike, but everything else is good) so it must be something i'm doing code wise and not necessarily a hardware issue.

This has plagued me for countless hours and I can't seem to come to a solution. This is my BalloonPattern class:

Note: This class references stage from my main gameloop, it does not create a second stage. There is only ever 1 stage in my game.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
public class BalloonPattern
{
   private Player player;
   private final Stage stage; //this stage is a reference to the main stage, not a new one.
 
   private int rows = 5; //all patterns must be 5 by 5
  private int cols = 5;
   
   /**
    * 1 = red balloon
    * 2 = blue balloon
    * 3 = yellow balloon
    */

   private int[][] line_center = {{0,0,1,0,0}, //middle line pattern
                       {0,0,1,0,0},
                        {0,0,1,0,0},
                        {0,0,1,0,0},
                        {0,0,1,0,0}};

   private int[][] diamond = {{0,0,1,0,0}, //diamond pattern
                       {0,1,0,1,0},
                        {1,0,2,0,1},
                        {0,1,0,1,0},
                        {0,0,1,0,0}};
   
   private int[][] heart = {{0,1,0,1,0}, //heart pattern
                       {1,1,1,1,1},
                        {1,1,2,1,1},
                        {0,1,1,1,0},
                        {0,0,1,0,0}};
   
   private int[][] upvote = {{0,0,1,0,0}, //upvote pattern
                       {0,1,1,1,0},
                        {1,1,1,1,1},
                        {0,0,1,0,0},
                        {0,0,1,0,0}};
   
   private int[][] scatter = {{0,1,0,1,0}, //scatter pattern
                       {1,0,1,0,1},
                        {0,1,0,1,0},
                        {1,0,1,0,1},
                        {0,1,0,1,0}};
   
   private int[][] sadface = {{0,0,0,0,0}, //sadface pattern
                       {0,2,0,2,0},
                        {0,0,0,0,0},
                        {0,1,1,1,0},
                        {1,0,0,0,1}};
   
   private int[][] TIE_fighter = {{1,0,0,0,1}, //TIE fighter pattern
                       {1,0,1,0,1},
                        {1,1,1,1,1},
                        {1,0,1,0,1},
                        {1,0,0,0,1}};
   
   private int[][] line_left = {{1,0,0,0,0}, //left column pattern
                       {1,0,0,0,0},
                        {1,0,0,0,0},
                        {1,0,0,0,0},
                        {1,0,0,0,0}};
   
   private int[][] line_right = {{0,0,0,0,1}, //right coloumn pattern
                       {0,0,0,0,1},
                        {0,0,0,0,1},
                        {0,0,0,0,1},
                        {0,0,0,0,1}};
   
   private int[][] wtf =    {{3,2,3,2,3},
                     {2,3,2,3,2},
                     {3,2,3,2,3},
                     {2,3,2,3,2},
                     {3,2,3,2,3}};

   private int[][] currentPattern;
   private HashMap<String, int[][]> patternMap;
   
   ArrayList<String> patternArray;
   
   public float x_loc;
   private float x_pattern; //the patterns x location
  private float y_pattern; //the patterns y location
  private float y_loc = 0;
   private float balloonWidth = 64;
   private float time = 0;
   private float spawnTime;
   
   private Group balloonGroup;
   SnapshotArray<Actor> balloons;
   
   public class RedBalloonPool extends Pool<Actor>{
      @Override
      protected RedBalloon newObject()
      {
         // TODO Auto-generated method stub
        return new RedBalloon(player, x_loc, y_loc, false);
      }
   }
   public class BlueBalloonPool extends Pool<Actor>{
      @Override
      protected BlueBalloon newObject()
      {
         // TODO Auto-generated method stub
        return new BlueBalloon(player, x_loc, y_loc, false);
      }
   }
   public class YellowBalloonPool extends Pool<Actor>{
      @Override
      protected YellowBalloon newObject()
      {
         // TODO Auto-generated method stub
        return new YellowBalloon(player, x_loc, y_loc, false);
      }
   }
   
   RedBalloonPool rbPool = new RedBalloonPool();
   BlueBalloonPool bbPool = new BlueBalloonPool();
   YellowBalloonPool ybPool = new YellowBalloonPool();
   
   /*
    * Thoughts: After the patten finishes, take a snapshot array, free the balloons to the pool.
    */

   
   /**
    *
    * @param p Reference to the {@link Player}
    * @param stage Reference to the parent {@link Stage}
    * @param time Interval in second before a new pattern is created
    */

   public BalloonPattern(Player p, Stage stage, float time)
   {
      this.player = p;
      this.stage = stage;
      spawnTime = time;
     
      patternMap = new HashMap<String, int[][]>();
     
      //add patterns to map
     patternMap.put("line",line_center);
      patternMap.put("line_right", line_right);
      patternMap.put("line_left", line_left);
      patternMap.put( "diamon",diamond);
      patternMap.put("heart",heart);
      patternMap.put("sadface",sadface);
      patternMap.put("upvote",upvote);
      patternMap.put("scatter",scatter);
      patternMap.put("TIE fighter",TIE_fighter);
      patternMap.put("wtf", wtf);
     
      patternArray = new ArrayList<String>(patternMap.keySet());
     
      /*
       * Add initial ballons to the pool
       */

     
      populatePools();
     
   }
   private void populatePools()
   {
      /*
       * This is an idea I had to give the pools some initial objects, so when the first pattern
       * is created, it wouldnt have lag. However, this did not help.
       */

      Balloon b;
      for(int i = 0; i < 15; i++)
      {
         if(i < 5) //add 5 blue and yellow ballons to the pool
        {
            b = bbPool.newObject();
            bbPool.free(b);
            b = ybPool.newObject();
            ybPool.free(b);
         }
         else //add 10 red balloons to the pool
        {
            b = rbPool.newObject();
            rbPool.free(b);
         }
      }
     
   }
   public void update()
   {
      time += Gdx.graphics.getDeltaTime();
      if(time > spawnTime)
      {
         x_pattern = MathUtils.random(Stratofall.WIDTH - (cols * balloonWidth));
         y_pattern = 0; //this will change depending on how many rows of the pattern contain a coin
       
         setPattern();
         time = 0;
      }
   }
   private void setPattern()
   {
      currentPattern = patternMap.get(patternArray.get(MathUtils.random(patternArray.size()-1)));
      createBalloons();
   }
   private void createBalloons()
   {
      Group temp = balloonGroup;
      /*
       * This method adds the old balloons to the pool to be re-used before creating the new group
       */

      freeBalloons(temp);
      /*
       * the size of our balloon is 64 so we need to make sure each balloon in the
       * group is offset by 64 and add them to the group.
       */

     
      balloonGroup = new Group();
      if(stage.getActors().contains(balloonGroup, true))
      {
         System.out.println("Does not contain a balloon group");
      }
      else
      {
         stage.getRoot().removeActor(temp); //remove the old balloon group
        stage.addActor(balloonGroup); //add the new balloon group
     }
     
      int[][] localArray = currentPattern; //the loop doesnt need to look up the pattern from memory
     
      /*
       * Creating a local array means that it doesnt need to look up the array
       * every loop from memory. Also, looping as done below is much faster than
       * using traditional for loops.
       *
       */

      Balloon balloon;
     
      for(int[] array:localArray)
      {
         x_loc = x_pattern;
         for(int num:array)
         {
            if(num == 1)
            {
               balloon = rbPool.newObject();
               balloon.allowReset(false);
               balloonGroup.addActor(balloon);
            }
            else if(num == 2)
            {
               balloon = bbPool.newObject();
               balloon.allowReset(false); //the balloon does not reset
              balloonGroup.addActor(balloon); //add the balloon to the group
           }
            else if(num == 3)
            {
               balloon = ybPool.newObject();
               balloon.allowReset(false);
               balloonGroup.addActor(balloon);
            }
            x_loc = x_loc + (balloonWidth);
         }
         y_loc = y_loc - (balloonWidth);
         y_pattern = y_loc;
      }
   }
   private void freeBalloons(Group balloonGroup)
   {
      /*
       * Before a new pattern is made, we free the balloons from the old
       * balloonGroup to be used in the new one.
       */

      if(balloonGroup != null)
      {
         balloons = balloonGroup.getChildren();
         if(balloons.size > 0) //there are balloons to free
        {
            for (Actor balloon : balloons)
            {
               /*
                * free each balloon to add to the pool
                */

               String name = balloon.getName();
               if(name.equals("red"))
               {
                  rbPool.free(balloon);
               }
               else if(name.equals("blue"))
               {
                  bbPool.free(balloon);
               }
               else if(name.equals("yellow"))
               {
                  ybPool.free(balloon);
               }
               else
                  System.out.println("ERROR: Balloon not added to pool!");
            }
         }
      }
     
   }
   public float getY()
   {
      return y_pattern;
   }
   public void setPattern(String pattern)
   {
      currentPattern = patternMap.get(pattern);
   }


Here is an example of how my BalloonPattern works in the game loop

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
/**
 *
 * @author Shane All game objects and HUD are drawn and displayed here.
 */


public class GameScreen implements Screen
{
   FPSLogger fpsLogger = new FPSLogger();

   private ParticleEffect dustEffect;

   private Player player;
   private Music gameMusic;
   private Texture backgroundImage;
   private ScrollingLayer backgroundLayer;
   private GameHud hud;

   private float background_y = -2560; // starting position
  private float background_rate = .25f; // the rate at which the background
                                // progresses up the screen

   // private BalloonPattern balloonPattern;

   private Stage stage;
   private Group cloudGroup, cloudGroup2, balloonGroup;
   private CloudManager cloudManager;
   private CloudManager cloudManager2;
   private BalloonManager balloonManager;
   private BalloonPattern balloonPattern;

   public GameScreen()
   {
      player = new Player();
      hud = new GameHud(player); // create a new instance of hud referencing
                          // player

      // load images
     backgroundImage = Stratofall.assets.get("backgrounds/background.jpg",
            Texture.class);
      backgroundLayer = new ScrollingLayer(backgroundImage, .85f);

      // load sounds (should be background noises, other sounds should be
     // loaded within their respective classes)
     gameMusic = Stratofall.assets.get("sounds/background/game_music.ogg",
            Music.class);
      gameMusic.setLooping(true);

      // load effects
     dustEffect = new ParticleEffect();
      dustEffect.load(Gdx.files.internal("particles/effects/dust.p"),
            Gdx.files.internal("particles/effects"));
      dustEffect.setPosition(Stratofall.WIDTH / 2, Stratofall.HEIGHT / 2); // center
                                                           // of
                                                           // screen
                                                           // at
                                                           // the
                                                           // bottom
     dustEffect.start();

      stage = new Stage(Stratofall.WIDTH, Stratofall.HEIGHT);
      Gdx.input.setInputProcessor(stage);

      cloudGroup = new Group();
      cloudGroup2 = new Group();
      balloonGroup = new Group();
     
     
      cloudManager2 = new CloudManager(cloudGroup2, player);
      cloudManager = new CloudManager(cloudGroup, player);
         cloudManager.setMaxNormalClouds(4);
         cloudManager.setMaxLightningClouds(1);
         cloudManager2.setMaxNormalClouds(4);
         cloudManager2.setMaxLightningClouds(0);
      stage.addActor(backgroundLayer);
      stage.addActor(cloudGroup2);
      stage.addActor(player);
      balloonPattern = new BalloonPattern(player, stage, 12);
      stage.addActor(balloonGroup);
      stage.addActor(cloudGroup);
     
      balloonManager = new BalloonManager(balloonGroup, player);
      //balloonManager.setMaxRedBalloon(100);
     stage.addActor(hud);

   }

   @Override
   public void render(float delta)
   {
      Gdx.gl.glClearColor(0.9f, 0.9f, 0.9f, 0f);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

      update();
      stage.act(delta);
      stage.draw();

      // fpsLogger.log();

      stage.getSpriteBatch().begin();
      dustEffect.draw(stage.getSpriteBatch(), delta);
      stage.getSpriteBatch().end();

   }

   private void update()
   {
      cloudManager.update();  //works perfectly, no noticeable lag
     cloudManager2.update(); //works perfectly, no noticeable lag
     balloonManager.update(); //works perfectly, no noticeable lag : balloonManager manages randomly spawned balloons. Nothing to do with BalloonPattern
     balloonPattern.update();


      if (player.getLives() == 0)
      {
         //System.gc();
        ((Game) Gdx.app.getApplicationListener())
               .setScreen(new FinalScoreScreen(player));
         dispose();
      }

      // keyboard input
     if (Gdx.input.isKeyPressed(Input.Keys.ESCAPE))
      {
         ((Game) Gdx.app.getApplicationListener())
               .setScreen(new MainMenuScreen());
         dispose();
      }

      if (Gdx.input.isKeyPressed(Input.Keys.F)) //testing purposes
     {
         ((Game) Gdx.app.getApplicationListener())
               .setScreen(new FinalScoreScreen(player));
         dispose();
      }

      if (Gdx.input.justTouched())
      {
         System.out.println(Gdx.input.getX() + ", "
               + (Gdx.graphics.getHeight() - Gdx.input.getY()));
      }
   }
}


Any ideas on why this might be happening to only my BalloonPatterns but nothing else? Possible fix?

Check out my Snipping Tool++ ! An advanced snippet/screenshot/text uploading tool! Meant to replace the windows snipping tool.

Check out Pixel Rain My most recent Swing based game!
Offline DemonWasp

Innocent Bystander





« Reply #1 - Posted 2013-11-21 02:01:54 »

I doubt that this is what's causing your stuttering problem, but it looks like you aren't using libGDX's Pools correctly. Instead of calling .newObject(), you should be calling .obtain(). You also don't have to "fill" the pool manually, you just use it. If it needs more instances than it contains, it will call .newObject() itself to generate them.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CogWheelz (17 views)
2014-08-01 22:53:16

CogWheelz (15 views)
2014-08-01 22:51:43

CopyableCougar4 (20 views)
2014-08-01 19:37:19

CogWheelz (19 views)
2014-07-30 21:08:39

Riven (27 views)
2014-07-29 18:09:19

Riven (16 views)
2014-07-29 18:08:52

Dwinin (14 views)
2014-07-29 10:59:34

E.R. Fleming (42 views)
2014-07-29 03:07:13

E.R. Fleming (13 views)
2014-07-29 03:06:25

pw (44 views)
2014-07-24 01:59:36
Resources for WIP games
by CogWheelz
2014-08-01 18:20:17

Resources for WIP games
by CogWheelz
2014-08-01 18:19:50

List of Learning Resources
by SilverTiger
2014-07-31 18:29:50

List of Learning Resources
by SilverTiger
2014-07-31 18:26:06

List of Learning Resources
by SilverTiger
2014-07-31 13:54:12

HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!