Monday, January 18, 2016

html5 - 2D maps, how to structure?


I'm new to this. And I don't really understand 2D tile maps.


The tutorials I've read use arrays, but doesn't this get really difficult to manage when they get big?


And what if I want different floors, like going up/down stairs, do I need an array for every "level" of the game world?



Could anyone explain tile based maps as simple as possible please? If you include code, please make it Javascript or pseudo code since it's all i know.



Answer



2D tile maps are exactly how they sound, imagine something like this:


1,1,1,1,1
1,0,0,0,1
1,0,2,0,1
1,0,0,0,1
1,1,0,1,1

This the design of our map and if we take



0 = floor
1 = wall
2 = chest

Then you can see that our map is a room with an entrance and a chest in the middle of the room our data structure for this could be like @georgeK said an Array of arrays ie.


var map =[ [1,1,1,1,1],
[1,0,0,0,1],
[1,0,2,0,1],
[1,0,0,0,1],
[1,1,0,1,1]];


We would then load each of our tiles into a look up just the once and draw our room by putting that tile in place of the number on the grid.


for row in map
for each cell in row
draw tile offset by the x, y position in the array multiplied by tile width.
end inner loop
end outer loop

Now you may not wish to draw this to the canvas directly and instead draw to a off DOM canvas and then transfer the entire image at once.


As a side note a 2d map based in html 5 has been done by google as proof of concept for a multiplayer game which could give you a few ideas on optimization. video here



Hope this helps


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...