VBfx / Tile tutorial / Step 6

Accessing the map

When editing the map we want to specify a position in 2D space (like x, y) and a tile we want to set there. So how can we find out where in the Data array that position is? Since we're using a 0-based data array this is getting quite easy, we only need the map width to get the corresponing index. In the following illustration you can see a 5x4 index map and one marked item at index 13:

Index map
01234
56789
1011121314
1516171919

The 0-based position of the yellow marked item is (3, 2) but the index is 13. So how do we get there? Multiplicate the Y-position by the map width, in our example that's (2 * 5) = 10. As you can see in the table we're now at the specified Y-position in the map (index 10 is the start of the line we need). So finally add the X-position to the result and here we are at (10 + 3) = 13!

Again, the basic idea is: Multiplicate Y by the width and add X to get the index. Note that this only works if both, array and position are 0-based!

Automation

To make things easier you should write a short function where you can pass X and Y and a tile index to edit the map. Its only one line of code but it makes life quite easier (this one goes into mMap):

Public Sub SetTile( iX as Long, iY as Long, Index as Long )
    'Set tile at the specified 0-based position
    Map.Data( iY * Map.W + iX ) = Index
End Sub

In case you prefer 1-based coordinates (where the first position in your map is (1, 1) instead of (0, 0)) you can simply modify this here. I do not recommend this but it's a nice example showing you how converter functions can be used to fit a program to your needs. The code would look like this:

Public Sub SetTile( iX as Long, iY as Long, Index as Long )
    'Set tile at the specified 1-based position
    Map.Data( ( iY - 1 ) * Map.W + iX - 1 ) = Index
End Sub

If you still want a 1-based array this shouldn't be too hard to implement now. But again, I highly recommend you to use 0-based arrays whenever possible which means: always!

Navigation