Workshop › Puzzle Bobble-style Bubble Shooter › Step 14 of 31
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
}
```snap looks at every empty cell and keeps the one with the smallest distance: { r, c, d }.attach writes the color into the cell.update, a shot that touches something snaps, attaches and is gone: shot = null, so the next one can be fired.function update() { write snap (with its comment) and attach, each followed by an empty line.update, under the wall block, write the if (touches(...)) block.Skills: Collision detection, Arrays and objects
← Touching something? Smaller steps →