Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda