Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function WorldToGridPos(self, WorldPos)
- local CellSize = self.CellSize
- local RoundedHalfCellSize = self.RoundedHalfCellSize
- local X = WorldPos.X + RoundedHalfCellSize.X
- local Y = (WorldPos.Z or WorldPos.Y) + RoundedHalfCellSize.Y
- return Vector2.new(
- math.floor( X / CellSize.X),
- math.floor( Y / CellSize.Y)
- )
- end
- local function CreateCell(self, CellPos)
- local Pos_X, Pos_Y = CellPos.X, CellPos.Y
- local Cells = self.Cells
- local Cell_X = Cells[Pos_X]
- if not Cell_X then
- Cell_X = {}
- Cells[Pos_X] = Cell_X
- end
- local Cell_Y = Cell_X[Pos_Y]
- if not Cell_Y then
- Cell_Y = {}
- Cell_X[Pos_Y] = Cell_Y
- end
- return Cell_Y
- end
- local function GetCell(self, CellPos)
- local Cell_X = self.Cells[CellPos.X]
- return Cell_X and Cell_X[CellPos.Y]
- end
- local function MoveObjectToCell(self, Object, CellPos, ObjectCacheName)
- local NewCell = self:CreateCell(CellPos)
- local ObjectToCell = self.ObjectToCell
- local OldCell = ObjectToCell[Object]
- local ObjectCache = ObjectCacheName == nil and NewCell or NewCell[ObjectCacheName]
- if not ObjectCache then
- ObjectCache = {}
- NewCell[ObjectCacheName] = ObjectCacheName
- end
- if OldCell then
- if OldCell[Object] then
- --stored in dictionary
- OldCell[Object] = nil
- else
- --stored in an array
- table.remove(OldCell, table.find(OldCell, Object))
- end
- end
- table.insert(ObjectCache, Object)
- ObjectToCell[Object] = ObjectCache
- end
- local function RegisterObject(self, Object, WorldPos, CacheName)
- local CellPos = self:WorldToGridPos(WorldPos)
- MoveObjectToCell(self, Object, CellPos, CacheName)
- return CellPos
- end
- local Module = {}
- function Module.new(CellSize)
- local Grid = {
- CellSize = CellSize,
- RoundedHalfCellSize = Vector2.new(math.floor(CellSize.X/2), math.floor(CellSize.Y/2)),
- Cells = {}, --[X][Z] = {}
- ObjectToCell = {}, --[Object] = Cell
- WorldToGridPos = WorldToGridPos,
- GetCell = GetCell,
- RegisterObject = RegisterObject,
- MoveObjectToCell = MoveObjectToCell,
- CreateCell = CreateCell,
- }
- return Grid
- end
- return Module
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement