- Home /
Moving a character into a 2d int array
Hi dear Unity community :)
I learn javascript through Unity for some months now so i sure have some gaps in my knowledge and i'm kind of stuck in my new project. It's a simple 2D tiled puzzle/plateformer. I'm planning to use @Eric5h5 GridMove and from my reading around here I understand the best way to build my game is to use an int array to store my level. Then here is a great example from @Statement found as an answer here : http://answers.unity3d.com/questions/51945/building-a-multidimensional-array-for-grid-movemen.html
private var width = 10;
private var height = 10;
private var grid = [
[1,1,1,1,1,0,1,1,1,1],
[1,0,0,0,1,1,1,0,0,1],
[1,1,1,0,0,1,0,0,1,1],
[1,0,1,1,1,1,1,1,1,0],
[1,0,0,0,1,0,1,0,1,0],
[1,1,1,1,1,0,1,1,1,1],
[0,0,1,0,1,1,1,0,0,1],
[1,1,1,1,1,0,1,1,0,1],
[1,0,0,1,0,0,0,1,0,1],
[1,1,1,1,1,1,1,1,1,1]
];
private var edges : Edges[,];
@System.Flags
enum Edges
{
None = 0,
East = 1,
North = 2,
West = 4,
South = 8,
// Edit: added Edges.All as shortcut for East|North|West|South
All = 15
};
// Let's build the edges so we don't need to do a lot of checking.
BuildEdges();
function BuildEdges()
{
edges = new Edges[width, height];
for (var y = 0; y < height; ++y)
{
for (var x = 0; x < width; ++x)
{
edges[x, y] = FindEdges(x, y);
}
}
}
function FindEdges(x : int, y : int) : Edges
{
var edge = Edges.None;
if (Grid(x, y - 1) == 1)
edge |= Edges.North;
if (Grid(x - 1, y) == 1)
edge |= Edges.West;
if (Grid(x + 1, y) == 1)
edge |= Edges.East;
if (Grid(x, y + 1) == 1)
edge |= Edges.South;
return edge;
}
function Grid(x : int, y : int) : int
{
if (x < 0 || x >= width) return 0;
if (y < 0 || y >= height) return 0;
return grid[x][y];
}
// Use Test as such:
// if (Test(x, y, Edges.West))
// MoveWest();
function Test(x : int, y : int, direction : Edges) : boolean
{
if (x < 0 || x >= width) return false;
if (y < 0 || y >= height) return false;
return (edges[x, y] & direction) == direction;
}
Here i don't understand the last part "function Test". Is it written just as an example ? Or is it done for specific purpose ? Do I have to write a function Test for each direction to know if my character can move ?
(edit) Another point, I don't get the use of the enum edges numbers.
Then, if i want to add other tiles functions, for example a ladder or a hole one, do I have to store it as a similar way in an new array ?
Sorry if i did something wrong, it's my first question here ^^'
The point of 'Test' is to make sure that you're not moving off the edge of the board. The 'edge' enum allows you to check which edges a given point is adjacent to.
ok then I have to write another script "function Test" to know if my character can move, right ? Sorry i've not been enough precise, but what's the use of the enum edge numbers ?