Workshop › Puzzle Bobble-style Bubble Shooter › Step 14 of 31

Stick into the grid

What we are doing

Where the shot stopped is almost never exactly a cell, so it snaps to the nearest empty cell. That one step turns free movement back into the grid, and everything after only has to think about cells.

```js
// The empty cell closest to where the bubble stopped.
function snap(x, y) {
  let nearest = null
  for (let r = 0; r < ROWS; r++) {
    for (let c = 0; c < cols(r); c++) {
      if (grid[r][c] >= 0) continue
      const p = cellPos(r, c)
      const d = Math.hypot(p.x - x, p.y - y)
      if (!nearest || d < nearest.d) nearest = { r, c, d }
    }
  }
  return nearest
}

function attach(r, c, color) {
  grid[r][c] = color
}

  if (touches(shot.x, shot.y)) {
    const cell = snap(shot.x, shot.y)
    attach(cell.r, cell.c, shot.color)
    shot = null
  }
```

What it means

Your turn

  1. Above function update() { write snap (with its comment) and attach, each followed by an empty line.
  2. In update, under the wall block, write the if (touches(...)) block.

Skills: Collision detection, Arrays and objects

All steps

  1. The night sky
  2. One bubble
  3. A grid of cells
  4. Draw the grid
  5. Bubbles that nest
  6. The shooter
  7. Aim upwards
  8. Turn with the arrows
  9. Aim with the pointer
  10. Fire!
  11. Fly
  12. Bounce off the walls
  13. Touching something?
  14. Stick into the grid
  15. Smaller steps
  16. Six neighbours
  17. Flood fill
  18. Three in a row pop
  19. Bubbles that fall
  20. Cut them loose
  21. Show the score
  22. Only useful colors
  23. Count the shots
  24. The ceiling comes down
  25. Win or lose
  26. The danger line
  27. The end message
  28. Play again
  29. Best score
  30. A dotted guide
  31. Build it yourself: swap bubbles