如何在Javascript中从平铺贴图中的一个点计算平铺

如何在Javascript中从平铺贴图中的一个点计算平铺,javascript,tile,Javascript,Tile,我有一个用纯JavaScript编写的Tilemap: 常量映射=[ 0,0,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1 ] 每个平铺渲染为128*128px正方形 我已经编写了一个函数,可以打印出两点之间的欧几里德距离,在我的例子中,就是平铺地图上点击事件之间的距离: 功能距离(x,y,x2,y2){ 返回Math.sqrt(Math.pow((x-x2),2)+Math.pow((y-y2),2)) } 如何计算单击发生在哪个分幅上?如果map表示一个4 x 4矩阵,则

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

常量映射=[
0,0,1,1,
1,1,1,1,
1,1,1,1,
1,1,1,1
]
每个平铺渲染为128*128px正方形

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

功能距离(x,y,x2,y2){
返回Math.sqrt(Math.pow((x-x2),2)+Math.pow((y-y2),2))
}

如何计算单击发生在哪个分幅上?

如果
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,1,1,1];
log(getIndex(0,0));

log(getIndex(1,0))假设你有一个矩阵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)
现在您可以使用您的功能:

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)