【问题标题】:How to calculate the tile from a point in the tile map in Javascript如何在Javascript中从瓦片地图中的一点计算瓦片
【发布时间】:2021-02-19 18:10:05
【问题描述】:

我有一个用纯 JavaScript 编写的 Tilemap:

const map = [
    0,0,1,1,
    1,1,1,1,
    1,1,1,1,
    1,1,1,1

]

每个图块呈现为 128*128px 正方形。

我已经编写了一个函数,可以打印出两点之间的欧几里得距离,在我的例子中是瓦片地图上点击事件之间的距离:

function distance(x,y,x2,y2) {
    return Math.sqrt(Math.pow((x-x2), 2)+Math.pow((y-y2), 2))
}

如何计算点击发生在哪个图块上?

【问题讨论】:

    标签: javascript tile


    【解决方案1】:

    如果map 表示一个 4 x 4 矩阵,您可以使用以下公式计算索引。

    const
        getIndex = (x, y) => x + 4 * y,
        map = [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
    
    console.log(getIndex(0, 0));
    console.log(getIndex(1, 0));

    【讨论】:

      【解决方案2】:

      假设你有一个矩阵 n x m n = 行数 m = 列数

      你将拥有一个包含 n * m 个值的数组

      所以要计算两点的欧几里得距离,你需要知道那个值的水平(x)指数和垂直(y)指数,例如:

      map = [1, 1, 1, 1] 
      // map[0] is in the position (0, 0)
      // map[1] is in the position (1, 0)
      // map[2] is in the position (0, 1)
      // map[3] is in the position (1, 1)
      

      你可以使用这个函数来做到这一点:

      const getX = (index, m) => index % m
      const getY = (index, n) => Math.floor(index / n)
      

      现在你可以使用你的函数了:

      let m = 128,
          n = 128,
          index = 0,
          index2 = 1,
          map = [// n * m values here],
          x, y, x1, y1
      
      x = getX(index, m)
      y = getY(index, n)
      x1 = getX(index1, m)
      y1 = getY(index1, n)
      
      d = distance(x, y , x1, y1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-15
        • 1970-01-01
        • 2013-04-15
        • 1970-01-01
        • 2014-03-17
        • 1970-01-01
        相关资源
        最近更新 更多