如何编写将值四舍五入到最接近的第 16 位的函数

How to write a function that rounds the value to nearest 16th

我正在尝试制作一个游戏,其中每个图块的高度和宽度均为 16。每当单击鼠标而不是以 1 为步长获取 x 和 y 值时,我希望它们以 16 为步长获取。

我想要在第 16 步中使用它的原因是我使用对象数组来存储所有图块。要获取数组的索引,我需要准确的 x 和 y 值。

步数1转换为步数16的代码:

x = math.floor(math.floor(math.floor(x/(8/3))/16)*16)-32

y = math.floor(math.floor(math.floor(y/(8/3))/16)*16)-48

x 和 y 来自函数 love.mousepressed(x,y,button)

试试这个

function round16(x)
  return 16*(math.floor(x/16+0.5))
end

或者 Lua 5.3+ 如果 x 是一个整数

function round16(x)
  return 16*((x+8)//16)
end