Home > OS >  Return coordinates (x,y) from an array of numbers in Javascript
Return coordinates (x,y) from an array of numbers in Javascript

Time:12-23

I am trying to make a collision map in a 2d top down view game in Javascript. I am using Tiled to build the maps. Tiled generates a json / javascript file with an array of each element in my map. I can set a boolean for each tile, so those with the true setting will come out in the array as 1 and those with the false value will return 0.

Now I want output those data as x,y coordenates. I mean if i have the array [0,0,0,0] I want that those output like (x,y) (0,0), (1,0), (2,0), (3,0) based in the width and height of the tilemap array. Something like this:

"data":[0,0,0,0,
        1,1,1,1,
        0,0,0,0,
        0,0,0,0]
"height":4,
"width":4,
"x":0,
"y":0

My problem is I don't know how to say it to my loop that there will be four columns and four rows and the index should change from (0,0), (0,1), (0,2), (0,3) to (1,0), (1,1),(1,2),(1,3) after end the first row continue until the last column.

Any idea?

CodePudding user response:

You could use two for-loops for the current row and col respectively:

const tiledOutputJson = {
    "data": [
        0, 0, 0, 0,
        1, 1, 1, 1,
        0, 0, 0, 0,
        0, 0, 0, 0
    ],
    "height": 4,
    "width": 4,
    "x": 0,
    "y": 0
};

const { data, height, width, x, y } = tiledOutputJson;

for (let row = 0; row < height; row  ) {
    for (let col = 0; col < width; col  ) {
        console.log(`(${row}, ${col}) = ${data[row * height   col]}`);
    }
    console.log();
}

CodePudding user response:

In general I would recommend to make it an array for x which contains the arrays for y

[
[0,0,0,0],
[1,1,1,1],
[0,0,0,0],
]

You can do the mapping like so

const data = {
  "data": [0, 0, 0, 0,
    1, 1, 1, 1,
    0, 0, 0, 0,
    0, 0, 0, 0
  ],
  "height": 4,
  "width": 4,
  "x": 0,
  "y": 0
}

for (let x = 0; x < data.height * data.width; x = x   data.width) {
  for (let y = x; y < data.width   x; y  ) {
    console.log({
      x: x / data.height,
      y: y % data.width,
      v: data.data[y]
    })
  }
}

  • Related