I am reading the source code of an existing platformer game and I came accross this:
/* assign the horizontal position of the TileMap on the screen to offsetX
* this, center aligns the player. */
int offsetX = width / 2 - Math.round(player.getX()) - TILE_SIZE;
/* stop the map scrolling if the player reaches the two ends
* of the map */
offsetX = Math.min(offsetX, 0); // if offsetX < 0 , offsetX = 0
offsetX = Math.min(offsetX, width-tileMap.getWidth()); //if offsetX > map width, offsetX = mapwidth
int offsetY = height - toPixels(tileMap.getHeight()); // not really necessary, I think
int firstTile = toTiles(-offsetX); // ???
int lastTile = firstTile + toTiles(width) + 1; // why the +1
I have commented some parts I think I understand, and asked questions about others in the comments.
The things that bother me most are:
1- how offsetX is assigned (width/2 ... ?
) I have understood that it assigns offsetX to some place on the map which center aligns the player, but I have no idea how.
2-In the 3rd line, why did the developer write width - tileMap.getWidth()
?
Note: If it is too troublesome to explain the code line by line, please give me a rough idea, perhaps with a diagram? of what the developer is trying to do here. thanks.
1-i think this offset is for drawing the tiles not for centering the player, this function increases the offset with a negative number when the player moves, the farther to the right he moves, the higher player.getX()
is, the higher the offset is.
example:
width=300
player.getX()=300
TILE_SIZE=10
tileMap[0]=(x,y)=(10,10)
offset=300/2-300-10
offset= -160
now this offset is used to draw the tiles with a negative offset, in other words, further left, in this case tileMap[0]=(10-160,10)
which means tileMap[0] is out of the screen range(tile scrolled to the left, player to the right)
2-i think this should be offsetX = Math.max(offsetX, width-tileMap.getWidth());
in that case its an extra check to only scroll to the end of the map.
example:
width=300
player.getX()=900
TILE_SIZE=10
tileMap[last]=(1010,10)
tileMap.getWidth()=1000
offset=300/2-900-10
offset= -760
offsetX = Math.min(-760, 0);
offsetX = -760
offsetX = Math.max(-760, 300-1000);
offsetX = -700