munificent / game-programming-patterns

Source repo for the book
http://gameprogrammingpatterns.com/
Other
4.12k stars 498 forks source link

Spatial Partition handleCell function should compare cell's coordinates not unit coordinates #344

Open itzjac opened 5 years ago

itzjac commented 5 years ago

When comparing if a Unit shares the same cell with Other Unit in the grid, the function handleCell compares Unit's 2D coords as double type. The Unit struct doesn't store cell's coordinates (2D unsigned int coords, the index in the grid). If 2D unsigned int coords are stored, those values can be used instead in the comparison.

class Unit
{
// Previous code...
public:
   unsigned cellX_;
   unsigned cellY_;
};

void Grid::add(Unit* unit)
{
// Determine which grid cell it's in.
  int cellX = (int)(unit->x_ / Grid::CELL_SIZE);
  int cellY = (int)(unit->y_ / Grid::CELL_SIZE);

  // Add to the front of list for the cell it's in.
  unit->prev_ = NULL;
  unit->next_ = cells_[cellX][cellY];

 // Add Unit grid coords
  unit->cellX_ = cellX;
  unit->cellY_ = cellY;
  cells_[cellX][cellY] = unit;

  if (unit->next_ != NULL)
  {
    unit->next_->prev_ = unit;
  }
}

void Grid::handleCell(Unit* unit)
{
  while (unit != NULL)
  {
    Unit* other = unit->next_;
    while (other != NULL)
    {
     if (unit->cellX_ == other->cellX_ &&
         unit->cellY_ == other->cellY_)
     {
         handleAttack(unit, other);
     }
      other = other->next_;
    }

    unit = unit->next_;
  }
}