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.
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
/**
*
* @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?