In my LibGDX game, I am trying to work out a way to create a map based on the pixels in a .PNG image file. I am using the BufferedImage class to convert and store the RGB values from the image into an Array, which then returns a Tile based on its value. However, the Array that contains all of the Tiles is just filled with 'null
' values.
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.survivegameandroidtest.survive.player.Player;
import com.survivegameandroidtest.survive.tiles.ConcreteTile;
import com.survivegameandroidtest.survive.tiles.GrassTile;
public class Level {
Tile[] tiles;
int[] levelPixels;
AssetManager manager;
Player player;
SpriteBatch batch;
public Level(String path) {
try {
BufferedImage image = ImageIO.read(Level.class.getResource(path));
int width = image.getWidth();
int height = image.getHeight();
tiles = new Tile[width * height];
levelPixels = new int[width * height];
image.getRGB(0, 0, width, height, levelPixels, 0, width);
} catch(IOException e) {
e.printStackTrace();
System.out.println("Level could not load");
}
}
//GRASS = 0x24ff00
//CONCRETE = 0x8b8b8b
public void generateLevel() {
for(int i = 0; i < levelPixels.length; i++) {
if(levelPixels[i] == 0x24ff) tiles[i] = new GrassTile(manager.get("grass.png", Texture.class), new Vector2(i * 10, i * 10), new Vector2(10,10));
if(levelPixels[i] == 0x8b8b8b) tiles[i] = new ConcreteTile(manager.get("concrete.png", Texture.class), new Vector2(i * 10, i * 10), new Vector2(10,10));
}
}
public void update() {
}
public void draw(SpriteBatch batch) {
}
}
If I add a System.out.println(tiles[1])
- this will print 'null' in the console.
This code below is in a separate class, where I call the generate method and store the tiles Array in an Iterator. In the draw method, an if-statement is used to determine whether the current Tile in the Iterator is null, if it is, then it doesn't draw/render the tile. On the game, there is only a white screen with my player, indicating that all of the values in the tiles[]
Array are equal to 'null'. If the if-statement was to be removed, I would get a NullPointerException
.
SHOW METHOD
level = new Level("/level.png");
tiles = new ArrayList<Tile>();
for(int i = 0; i < level.tiles.length; i++) {
level.generateLevel();
tiles.add(level.tiles[i]);
}
RENDER METHOD
tileIterator = tiles.iterator();
while(tileIterator.hasNext()) {
final Tile cur = tileIterator.next();
if(cur != null) {
cur.update();
cur.draw(batch);
}
}
If I add:
if (levelPixels[i] != 0x24ff || levelPixels[i] != 0x8b8b8b) {
tiles[i] = new GrassTile(manager.get("grass.png", Texture.class),
new Vector2(i * 10, i * 10),
new Vector2(10, 10));
}
Then I receive a NullPointerException
.