Hey guys!
I’m trying to generate large tile maps from a 2D array in for loops:
package com.elements.world;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
import com.elements.gameobject.entity.Entity;
import com.elements.gameobject.tile.Tile;
public class Level {
public Tile[][] Tiles;
public Level(String name) {
Tiles = new Tile[50][50];
for (int x = 0; x < Tiles.length; x++) {
for (int y = 0; y < Tiles[0].length; y++) {
Tiles[x][y] = new Tile(new Rectangle(x * 32, y * 32, 32, 32));
}
}
}
public void Generate() {
for (int y = 0; y < Tiles.length; y++) {
for (int x = 0; x < Tiles[0].length; x++) {
Tiles[x][y].setTileID("elements:air");
if (y > 50 / 4) {
try {
if (Tiles[x-1][y-1].getTileID() == "elements:dirt") {
Tiles[x][y].setTileID("elements:dirt");
}
} catch (Exception e) {}
try {
if (Tiles[x+1][y-1].getTileID() == "elements:dirt") {
Tiles[x][y].setTileID("elements:dirt");
}
} catch (Exception e) {}
try {
if (Tiles[x][y-1].getTileID() == "elements:dirt") {
Tiles[x][y].setTileID("elements:dirt");
}
} catch (Exception e) {}
if (new Random().nextInt(120) < 20) {
Tiles[x][y].setTileID("elements:dirt");
}
}
}
}
}
/* Unused. */
public void AddEntity(Entity entity) {}
public void renderEntites(Graphics g) {}
public void renderTiles(Graphics g) {}
}
I’m aware 50x50 isn’t that big, so when I try to do 3000x3000, for example, the game lags really badly. I’m wondering if this is because I’m generating all of the tiles at once and storing them in memory? If so, how would I go about generating only some at a time?
By the way, here is the paint method and how they’re being drawn:
/* Our render method. */
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int xOffset = (int)player.Coordinates.x - (GAME_WIDTH / 2);
int yOffset = (int)player.Coordinates.y - (GAME_HEIGHT / 2);
this.cameraView = new Rectangle(xOffset, yOffset, GAME_WIDTH, GAME_HEIGHT);
g2d.translate(camera.getX(), camera.getY());
this.player.render(g);
for (int x = 0; x < level.Tiles.length; x++) {
for (int y = 0; y < level.Tiles[0].length; y++) {
if (cameraView.contains(x*32, y*32)) { // I thought this would fix the problem, if I were to render only what was in view but it didn't fix it.
level.Tiles[x][y].render(g);
}
}
}
g2d.translate(-camera.getX(), -camera.getY());
}
Any help?