Hi Guys!
I have a scrolling game. The camera.position.y is incremented over time.
Each time , the game generates bodies 1 screen ahead of the player so it looks the asteroids were there beforehand.
The problem is, each time they are generated, the FPS drops Which i suppose, its because of the bodies collision on generation.
What can i do?
/**
*
* @author André V Lopes
*/
public class EnemyGenerator {
private int MAX_BODIES_SPAWN = 30;
private Vector3 tmp;
/**
* Size of the screen to be filled with enemies
*/
private float SCREEN_HEIGHT;
/**
* Returns the position of the camera position Y-axis when the last call to
* enemy generated was started.
*/
private float LAST_CAMERA_POSITION_Y_ENEMY_GENERATED;
/**
* Return falses if update was never called
*/
private boolean hasStarted = false;
/**
*
* @param level
*/
public EnemyGenerator(Level level) {
tmp = new Vector3();
SCREEN_HEIGHT = ApplicationConfiguration.getHeight() * PTM;
}
public void update(Level level) {
if (!hasStarted) {
LAST_CAMERA_POSITION_Y_ENEMY_GENERATED = level.getViewport().getCamera().position.y;
generateEnemies(level);
hasStarted = true;
}
float y = level.getViewport().getCamera().position.y;
float difference = Math.abs(y - LAST_CAMERA_POSITION_Y_ENEMY_GENERATED);
System.out.println("Screen_Height =" + SCREEN_HEIGHT);
System.out.println("LAST_CAMERA_POSITION_Y_ENEMY_GENERATED =" + LAST_CAMERA_POSITION_Y_ENEMY_GENERATED);
System.out.println("Difference : " + difference);
if (difference >= SCREEN_HEIGHT) {
System.out.println("Generating Enemies...");
generateEnemies(level);
}
}
private void generateEnemies(Level level) {
LAST_CAMERA_POSITION_Y_ENEMY_GENERATED = level.getViewport().getCamera().position.y;
for (int i = 0; i < MAX_BODIES_SPAWN; i++) {
int randomEnemy = randomEnemy();
Vector3 randomPosition = randomPosition(level);
if (randomEnemy == GameObject.ASTEROID) {
Asteroid asteroid = new Asteroid();
asteroid.addAsteroid(level.getWorld(), randomPosition.x, randomPosition.y);
}
if (randomEnemy == GameObject.GIANT_ASTEROID) {
GiantAsteroid giantAsteroid = new GiantAsteroid();
giantAsteroid.addAsteroid(level.getWorld(), randomPosition.x, randomPosition.y);
}
}
}
public Vector3 randomPosition(Level level) {
Camera camera = level.getViewport().getCamera();
tmp.set(0, -Gdx.graphics.getHeight() * 0.2f, 0f); // bottom | left
camera.unproject(tmp);
float lowerX = tmp.x;
float lowerY = tmp.y;
tmp.set(Gdx.graphics.getWidth(), -Gdx.graphics.getHeight(), 0f); // top right + 1 screen
camera.unproject(tmp);
float upperX = tmp.x;
float upperY = tmp.y;
tmp.y = MathUtils.random(lowerY, upperY);
tmp.x = MathUtils.random(lowerX, upperX);
return tmp;
}