Trying to do some basic game development.
var = mapArray
is a 2D array which is filled with random numbers. Random numbers are important and I do not want to come up with a pre-defined 2D array.
Numbers are assigned to relevant images and then printed to form a tile map which is essentially a <canvas>
element:
for (var i = 0; i < mapArray.length; i++) {
for (var j = 0; j < mapArray[i].length; j++){
if (mapArray[i][j] === 0) {
context.drawImage(grass, posX, posY, 60, 60);
}
else if (mapArray[i][j] === 1) {
context.drawImage(forest, posX, posY, 60, 60);
}
else if (mapArray[i][j] === 2) {
context.drawImage(hills, posX, posY, 60, 60);
}
else if (mapArray[i][j] === 3) {
context.drawImage(mountains, posX, posY, 60, 60);
}
else if (mapArray[i][j] === 4) {
context.drawImage(swamp, posX, posY, 60, 60);
}
else if (mapArray[i][j] === 5) {
context.drawImage(forest, posX, posY, 60, 60);
}
posX+=60;
}
posX = 0;
posY+=60;
}
I am able to track mouse clicks on the entire canvas relative to its position on the page and get correct X and Y coordinates of a click.
Now I need to actually link the click coordinates with the tiles kept in the 2D array. It is important for me to know which tile is clicked since it will invoke different behavior (e.g. resources, enemies, events, etc).
I am entirely at a loss here and have been reading a lot these days. I might need to call every element's function and then check coordinates of each element within array against mouse coordinates as IF statement within the function, or I might broadcast mouse coordinates across all elements to see which one will respond. This does not seem to be a problem (at least for now, he he).
My problem is the following: how can I assign functions and other attributes to elements in my array, provided that those are images. May be the way I am building my array in is originally faulty, as I populate it with pure numbers and then translate numbers to images? I might possibly need to push objects with some more properties? How would I handle this situation?