proximityManager

useful for finding neighbors

by not important

HTML

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

CoffeeScript

class ProximityManager
    constructor: (@gridWidth, @gridHeight, totalWidth, totalHeight) ->
        @worldWidth = totalWidth / @gridWidth
        @worldHeight = totalHeight / @gridHeight
        @entities = {}
        @positions = []
        @cachedResults = []

    addEntity: (entityModel) ->
        @entities[entityModel.uniqueId] = entityModel

    removeEntity: (entityModel) ->
        delete @entities[entityModel.uniqueId]

    getNeighbors: (entityModel) ->
        x = Math.floor entityModel.x / @gridWidth
        y = Math.floor entityModel.y / @gridHeight
        index = y * @worldWidth + x

        results = @positions[index] or []

        clamp = (index, size) -> (index + size) % size
        cX = (index) => clamp index, @worldWidth
        cY = (index) => clamp index, @worldHeight
        addResult = (index) => results = results.concat(@positions[index]) if @positions[index]
        toIndex = (x, y) => cY(y) * @worldWidth + cX(x)

        addResult toIndex x - 1, y - 1
        addResult toIndex x, y - 1
        addResult toIndex x + 1, y - 1

        addResult toIndex x - 1, y
        addResult toIndex x + 1, y

        addResult toIndex x - 1, y + 1
        addResult toIndex x, y + 1
        addResult toIndex x + 1, y + 1

        @cachedResults = []

        results

    refresh: ->
        for uniqueId, entityModel of @entities
            x = Math.floor entityModel.x / @gridWidth
            y = Math.floor entityModel.y / @gridHeight
            index = y * @worldWidth + x

            if @positions[index] is undefined
                @positions[index] = [entityModel]
            else
                @positions[index].push entityModel

        @cachedResults = []

class EntityModel
    constructor: (@uniqueId, @x, @y) ->

$ ->
    proximityManager = new ProximityManager 3, 3, 12, 12

    entityA = new EntityModel 0, 7, 7
    entityB = new EntityModel 1, 3, 5
    entityC = new EntityModel 2, 10, 0
    entityD = new EntityModel 3, 7, 10
    entityE...