Worm | Collision detection with fruit.
Since we are using a tileset for all the game mechanics, a collision object is useless in this situation. Instead we will handle the game objects colliding by examining the tile map in code.
- In the assets panel, in the 'main' folder, double click, 'worm1.script'.
- In the create_new_head function, after the 'handle wrapping around the screen' section, but before the 'only update if the worm is alive' section, add the collision handling code.
-- Collision handling
local new_head_tile = tilemap.get_tile("/field#tilemap", "layer1", new_head.x, new_head.y)
-- Eat food
if new_head_tile == 45 then
self.grow = true
msg.post("/food#food","spawn_food")
end
What does this code do?
If the tile at the new head position is food (tile 45 in the tile source) then we set a flag to grow the worm in this update (not coded yet) and post a message to the food script telling it to spawn a new piece of food.
You could easily add new food types and scoring in this code section later.
- Save the changes by pressing CTRL-S or 'File', 'Save All'.
- Run the program by pressing F5 or choosing, 'Debug', 'Start / Attach' from the menu bar. You should be able to select '1up' and collect apples. The worm won't grow yet.
The next stage is to grow the worm when the apple is eaten. Stage 5c >