Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Return coordinates (x,y) from an array of numbers in Javascript

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!