简体   繁体   English

如何从 Javascript 中的瓦片 map 中的一点计算瓦片

[英]How to calculate the tile from a point in the tile map in Javascript

I have a Tilemap written in plain JavaScript:我有一个用普通 JavaScript 编写的 Tilemap:

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

]

Each tile is rendered as 128*128px square.每个图块渲染为 128*128px 正方形。

And I have written a function that prints out the euclidean distance between two points, in my case the distance between a click event on the tile map:我写了一个 function 打印出两点之间的欧几里德距离,在我的例子中,是 map 上的点击事件之间的距离:

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

How do I calculate on which of the tiles the click occured?如何计算点击发生在哪个图块上?

If map represents a 4 x 4 matrix, you could calculate the index with the following formula.如果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));

supose you have a matrix nxm where n = number of rows m = number of columns假设您有一个矩阵 nxm,其中 n = 行数 m = 列数

you will have a array with n * m values你将有一个包含 n * m 值的数组

So to calculate the euclidian distance of two points, you will need to know the horizontal (x) index and vertical (y) index of that value, for example:因此,要计算两点的欧几里德距离,您需要知道该值的水平 (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)

You can do this using this function:您可以使用此 function 执行此操作:

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

now you can use your function:现在您可以使用您的 function:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM