0
\$\begingroup\$

I am creating a basic tile-based 2D game ~mostly from scratch in Java, however all I need is pseudo-code for how this could be achieved.  My problem lies in the fact that my world (stored in a HashMap so I don't have to have a null object for every position down to 0) maybe millions or even billions of tiles large, so I'm sure it is not efficient to loop through every tile.  

A solution I have thought of to solve this issue would be to try to calculate based on the position of the camera in the world and the size of the tiles how many could fit on the screen in the X and Y axes, and also the offset of them to the screen as well, but I have tried (and failed) to implement this, because I am unsure on how to convert this is Maths/Logic.

How may I go about this? Below I have linked an image showing what tiles I intend to show to the screen, where the black square is the centre and tiles that do not cover the screen are not shown.

Diagram of what I want

\$\endgroup\$
1
\$\begingroup\$

Using a simple truncation as suggested by @Pikalek does only work with positive numbers. Truncating positive numbers is equivalent to the floor-operator but with negative numbers it is equivalent to the ceil- operator. To make it properly work in both cases you need to explicitly use the floor operation.

leftCameraBorder = centerX - camera.width / 2
leftCoordinate = Math.floorDiv(leftCameraBorder, tileSizeX)

Use the same code with changed variables for the top border.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Converting any coord to a tile is done by dividing by the tile size & discarding the decimal part.

So for instance, the camera focus will be in tile:

cameraTileX = (int)(cameraX / tileSizeX);
cameraTileY = (int)(cameraY / tileSizeY);

From there, you can calculate the upper leftmost tile (subtract half the screen size to the camera coord) & the lower rightmost tile (add half the screen size to the camera coord).

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.