Last Good Quote: Son's are the seasoning on our lives. - Someone on Facebook

Friday, April 2

Code: Simple 2D Javascript Map - Part 3

All right, let's put a character on the board!

It's not difficult, first we create a function that will add the character for us. So we know that we will need to know the following:
  • A distinct ID for the unit (unitID)
  • The x and y of where to place the unit.


Things to note:
  • We have to get the tile at X, Y.
  • We set the new div's tile to the Top and Left of the tile
  • We give the div tag a distinct "ID"
  • We give the new div tag a class of "unit"



function addUnit(unitID, x,y)
{
var d = document.createElement("DIV");
var tile = document.getElementById("tile_" + x + "_" + y)
d.className="unit";
d.setAttribute("ID","unit_" + unitID);
d.style.top = tile.style.top;
d.style.left = tile.style.left;
d.style.width = tileSize;
d.style.height = tileSize;
document.getElementById("divMap").appendChild(d);
}


We've created a new css class "unit" so we need to add the following to our styles:


.unit {
background:green;
border:1px solid #999;
position:absolute;
top:0px;left:0px;
width:5px;height:5px;
overflow:hidden
}


Finally, we actually add the unit to the map when the body is loading.

</script>
<body onload="buildMap(10,10); addUnit(1000,4,4)">


So the full page, looks like this...


<html>
<style>
.tile {
background:#BBB;
border:1px solid #999;
position:absolute;
top:0px;left:0px;
width:5px;height:5px;
overflow:hidden
}

.unit {
background:green;
border:1px solid #999;
position:absolute;
top:0px;left:0px;
width:5px;height:5px;
overflow:hidden
}
</style>
<script language=javascript>

var originX = 0;
var originY = 0;
var tileSize = 32;

function buildMap(width, height)
{
for(x=0;x<width;x++)
for(y=0;y<height;y++)
{
var d = document.createElement("DIV");
d.className="tile";
d.setAttribute("ID","tile_" + x + "_" + y);
d.style.top = originY + (y*tileSize);
d.style.left = originX + (x*tileSize);
d.style.width = tileSize;
d.style.height = tileSize;
d.setAttribute("onclick","tileClicked(" + x + "," + y + ")")
document.getElementById("divMap").appendChild(d);
}
}

function tileClicked(x,y)
{
var tile = document.getElementById("tile_" + x + "_" + y)
tile.style.background = "yellow"
}

function addUnit(unitID, x,y)
{
var d = document.createElement("DIV");
var tile = document.getElementById("tile_" + x + "_" + y)
d.className="unit";
d.setAttribute("ID","unit_" + unitID);
d.style.top = tile.style.top;
d.style.left = tile.style.left;
d.style.width = tileSize;
d.style.height = tileSize;
document.getElementById("divMap").appendChild(d);
}

</script>
<body onload="buildMap(10,10); addUnit(1000,4,4)">

<div id="divMap"></div>

</body>
</html>

0 comments:

Post a Comment

Followers