Wednesday, October 21, 2015

Cell division of map

Originally, to detect if bullets were colliding with other game entities, I would loop through the whole list of entities checking for collision on each one. This was super slow and it made the server lag every time a bullet was fired. A friend of mine gave me the solution of dividing the map into cells.

Now the map is divided into cells and held in a dictionary. It's created empty like so:

var m = make(map[int][]interface{})

And then, when an entity is added to the game, it also get's added to the dictionary like this:

var xCell = math.Floor(pos.x/CELL_SIZE)
var yCell = math.Floor(pos.y/CELL_SIZE)
var key int = int(xCell) * 1000 + int(yCell)

m[key] = append(m[key], entity)


It calculates the key by getting x and y coordinates from the entities position. It then creates a new array at that key's location in the dictionary. This means that there will only be as many cells as needed which makes looping over them super efficient.

When a bullet is in a cell, it only needs to check for collisions with players in that cell.

This was pretty fun to implement and made the server a lot more efficient:)

No comments:

Post a Comment