Ok next step is using world2map.
World2map is a function. If you give it coordinates in "world space" (such as the player's x and y) it will give you the map coordinates of the cell they occupy.
So if you want to know in what tile the player is, you can now do this:
Code: Select all
local tileX, tileY = world2map( player_X, player_Y )
With that information, it is quite easy to know the coordinates of the tile to the left of the player.
Code: Select all
local leftTileX, leftTileY = tileX - 1, tileY
If you want to know if there is a 'solid tile' on the left, you can do this:
Code: Select all
local leftTileNo = map[leftTileY][leftTileX] -- will return 0,1,2,3 etc (remember, 'y' goes first when using the map variable)
So your exercise now is changing the function that modifies the player position (depending on your implementation, love.update or love.keypress) so it checks whether the player can move to the left or right:
- Start by calculating tileX, tileY, leftTileX, leftTileY and leftTileNo as shown above.
- Then calculate the coordinates of the cell to the right of the player (rightTileX, rightTileY) and the number inside that cell (rightTileNo) (Use the calculations of the left tile as a model)
- Once you have leftTileNo and rightTileNo, use them to limit your player movement to the left and right. If you are saying "If the left key is pressed, decrement player_X", now you will have to say "If the left key is pressed and the left tile is air, decrement player_X". And the same for the right.
The "left tile is air" will depend on how you code your tiles. If you have assigned the number '0' to traversable tiles, then you have to compare leftTileNo with 0.
Once you have done all this, your player should (hopefully) be unable to traverse walls horizontally.