计算网格上实体位置(笛卡尔坐标),当实体和地面瓷砖的尺寸不同时

我正在尝试编写一个函数,告诉我玩家踩在哪个瓷砖上,已知 [ 地面瓷砖的尺寸 ] 不同于 [ 玩家瓷砖的尺寸 ]

我想要不惜一切代价避免循环整个地图

不幸的是,我没有数学的水平,这意味着我不知道如何做到这一点。

我正在使用 2D 经典笛卡尔坐标系,就像任何经典 RPG 一样。

我试图计算我的玩家所在的第一个瓷砖,然后我迷失了方向。我无法再做更多了。

我做了像这样的事情:i = math.floor( entity.x / tile size ) Same for j

then index = ( i + 1 ) + j * nbTilesPerRow

实际结果:什么也没有。连我从上述公式得到的 [ 瓷砖索引 ] 都没有被发现。


function Map:ClickedTile( mouseX, mouseY )
    local i = math.floor( mouseX / self.tile.size )
    local j = math.floor( mouseY / self.tile.size )

    local index = i + j * self.tile.width

    return index
end

这段代码可以运行,并且给我点击的瓷砖索引。

我想要复制这个过程,找出所有玩家目前正在碰撞的瓷砖,同时避免循环整个地图。

样例数据:

瓷砖尺寸 = 32 * 32
玩家瓷砖尺寸 = 64 * 64
地图尺寸:25 * 19

感谢您的阅读。

点赞
用户2689640
用户2689640

如果我理解正确的话,您希望在正方形{x=entity.x,y=entity.y,size=64}中获得地图瓦片。

获取所有位置:

function getPosition(map, square)
   local xpos = {}
   for i = square.x, square.x + square.size, map.tile.size do
      table.insert(xpos, math.floor(i / map.tile.size))
   end

   local ypos = {}
   for i = square.y, square.y + square.size, map.tile.size do
      table.insert(ypos, math.floor(i / map.tile.size))
   end
   return xpos, ypos
end

这样,您就可以在地图上得到正方形相交的所有{x,y}位置 (例如对于位置square = {x = 33,y = 33,size = 64},您可以得到xpos = {1,2,3})

然后您需要将x,y坐标转换为索引:

function positionToIndex(positions, mapWidth)
   local indexes = {}
   for position in ipairs(positions) do
      local index = i + j * mapWidth
      table.insert(indexes, index)
   end
   return indexes
end

local xpos,ypos = getPosition(map,entity)
local position = listOfCoordinate(xpos,ypos)- 应该是很简单的
local intersectionIndexes = positionToIndex(position,map.tile.size)

这有一些缺陷需要解决:

  • 当玩家恰好在瓦片上时,循环包括边界({x = 0,y = 0,size = 64}),他是否触摸瓦片0,1,2或0,1?
  • 这些数学是为0索引数组而设计的
  • 改变大小以按矩形的宽度/高度工作
2019-10-25 01:40:22