Reputation: 147
I have a Tilemap written in plain JavaScript:
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.
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 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?
Upvotes: 1
Views: 326
Reputation: 478
supose you have a matrix n x m where n = number of rows m = number of columns
you will have a array with n * m values
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:
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:
const getX = (index, m) => index % m
const getY = (index, n) => Math.floor(index / n)
now you can use your 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)
Upvotes: 1
Reputation: 386670
If map
represents a 4 x 4 matrix, you could calculate the index with the following formula.
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));
Upvotes: 1