# How to render a large tile-based 2D world efficiently (using JavaFX/ScalaFX or more generally)

I have a file tileset.png containing a dozen 32*32 tiles. When my game starts, it generates the world randomly with the available tiles and the size of the world can be changed, so I cannot have a hard-coded world texture.

So I have an $n \times m$ matrix, each of its element being a Tile. For the moment a so-called Tile is an ImageView(in JavaFX), which basically is a portion of my tileset (note that I only load the tileset image once and then generate all my tiles using it).

Now the very basic method that I'm using is, I store a boolean for each tile saying whether it is currently displayed on the screen. I also keep track of the total scale, that is the total amount of pixels that have been dragged yet. From this, for each tile that is to be displayed on the screen, I compute its $(x,y)$ position given the total offset and I add it to the scenne. Also for each tile that was displayed at the previous "iteration" but is not anymore, I remove it from the scene.

It is however quite laggy, especially when a lot of tiles need to be displayed at the same time or when dragging the map a lot.

I am sure I can drastically improve the performances but I cannot find how. I guess that having a different object for each tile isn't very efficient, yet as said before, I cannot have the entire map as a single image as it is randomly generated. So.. I still need each tile to be an object somehow?

I also saw a few things about using meshes or UV-mapping but I didn't really understand how to make it work here. Also, it was help for Unity. If anyone knows how to implement this in JavaFX/ScalaFX I would be glad to know, but otherwise I think I could adapt a general method in this specific library.

• I think you're only slowing things down with constantly adding/removing nodes from the scene. JavaFX already takes care of that for you by using dirty region optimizations (nodes that are off-screen or that don't change aren't rendered again every frame). You could also try to draw several nodes into one bigger tile with WritableImage when building your map. If JavaFX in general is not fast enough for you, have a look at LibGDX or JMonkeyEngine. – Ignatiamus Apr 5 '18 at 8:49

You can draw your tiles with the Canvas node. You can still use your tile set for this method. You just have to call the drawImage(image, sX, sY, sW, sH, dX, dY, dW, dH) method from the GraphicsContext of the canvas node. The s parameters are for defining a view on your image (like an ImageView). The d parameters are for sizing and positiong the resulting image on the canvas.