1

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?

1
  • Nested loops? It's not clear what the specific issue is. Commented Dec 23, 2021 at 0:23

2 Answers 2

2

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();
}

Sign up to request clarification or add additional context in comments.

1 Comment

I had been thinking about it for hours without knowing that I could do it with a nested loop. Thanks for the help!
0

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]
    })
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.