I have a cube grid made of an array of arrays in javascript. The grid dimensions are stored in variables. So dim is the dimension of the single cube, spacing is the distance between each cube (dim and spacing expressed in pixels).
Now, considering that I can always have the user mouse position in the variables g.mouseX and g.mouseY why this code isn’t always so precise?
var j = Math.round(g.mouseX / (dim+spacing));
var i = Math.round(g.mouseY / (dim+spacing));
// user clicked on the cell grid[j][i]
Sometimes I click a cube but it looks like he’s considering the one nearby. It looks like the whole mapping of the user click is shifted of half a dim. Probably using Math.round makes everything almost wrong, but I don’t see any other way to transform such a chaotic and unpredictable value as the user click to a precise coordinate in my grid.
Hope anyone can help on this!
Thanks in advance…
You want to truncate, not round. You can use
Math.floor, which maps (e.g.)3.7to3:But really, why not just bind the
onclickevent of each grid cell?