Workshop › Snake › Step 19 of 28
A snake cannot turn straight back into its own neck. We ignore the opposite direction, and keep the chosen turn
in nextDir until the snake actually moves.
```js
let nextDir = dir
// Ignore a turn straight back into the snake's own neck.
if (turn.x === -dir.x && turn.y === -dir.y) return
nextDir = turn
function update() {
dir = nextDir
```{ x: 1, y: 0 } is { x: -1, y: 0 }: both numbers negated. If the new turn is exactly that, ignore it.nextDir; update copies it into dir right before moving, once per move.let dir = ... write let nextDir = dir.dir = turn to nextDir = turn.dir = nextDir the first line of update.Skills: Keyboard and mouse input, Game states
← A table of turns Crash into the walls →