game-programming-patterns icon indicating copy to clipboard operation
game-programming-patterns copied to clipboard

Spatial partition example could use some more explanation of CELL_SIZE

Open Stalkstalks opened this issue 11 years ago • 1 comments

Great book, you do a good job of making things easy to understand.

However, when I got to this bit of code, I couldn't make sense of it for some time.

in void Grid::add(Unit* unit) about 40% of the way through the chapter, the following code is used to determine which cell in the grid a unit is in: int cellX = (int)(unit->x_ / Grid::CELL_SIZE); int cellY = (int)(unit->y_ / Grid::CELL_SIZE);

Grid::CELL_SIZE is set to 20, the grid is 10*10 in size.

The unit x_ and y_ are doubles indicating the position of the unit.

This didn't make sense to me. Why would CELL_SIZE have anything to do with the arbitrary position of the units? CELL_SIZE has had no role so far in the code or the discussion.

After staring at the rest of the code (and your commentary on the side) for a while, I think that you meant it to be understood that the cells were not central to the game (unit movement was not discrete between cells but fluid) but that they were central to the engine (the game's maps would be fixed at 200x200 by multiplying the cell size by the cell count).

I'm sure it was obvious to you, but this was only obvious to me after I bothered writing this out and trying to explain my confusion, because there is no mention of how CELL_SIZE is used before this. (I was asking myself "What if the map is 1,000 units across? Or 10,000? Don't you have to divide by the actual scale and then multiply by the number of cells? Location has no scale given. If it's just proportional to the map size you'd need to multiply the (presumably percentage) location with the cell count to find the cell it's in.")

This tripped me up for a bit and I spent entirely too much time thinking about it instead of continuing with the subject of the chapter.

Stalkstalks avatar Aug 28 '14 22:08 Stalkstalks

Don't you have to divide by the actual scale and then multiply by the number of cells?

You know, that's a good point. It might have been clearer if I had made the constant NUM_CELLS instead of the size of a single cell, and then scale from there. I did add an aside that I hope clarifies a bit, but you're probably right that this is confusing.

Alas, I think it's a bit too late in the production process of the book (I just sent the print version out to get a proof printed), so I'm hesitant to make any changes that are corrections of things that are truly wrong. Switching this to NUM_CELLS would be a pretty big change which would require me to go back and re-layout pages, etc.

I'll leave this open in case I find a good opportunity to make bigger changes, but I won't do anything about this for a while.

munificent avatar Sep 28 '14 01:09 munificent