Worm | Colliding with other game objects.

The worm should die if it hits anything except food.

  1. In the assets panel, in the 'main' folder, double click, 'worm1.script'.
  2. In the 'create_new_head' function, find the collision handling section. (See how useful comments in code are!)
  3. After the line, 'msg.post("/food#food","spawn_food")' but before, 'end', add this new condition.

	elseif new_head_tile ~=15 then
		self.alive = false
		tilemap.set_tile("/field#tilemap", "layer1", new_head.x, new_head.y, 60)
		msg.post("main:/controller#main", "worm_died")
What does this code do?

If the tile at the new head position is anything except grass (tile 15 in the tile source) the worm is no longer alive.

The head is replaced with a skull and crossbones icon (tile 60) so the player can see where they died.

A message is sent to the game controller to say that a worm has died.

Now that the worm is dead the remainder of the worm will be left in play as an object to be avoided by the other players.

  1. Save the changes by pressing CTRL-S or 'File', 'Save All'.
  2. Run the program by pressing F5 or choosing, 'Debug', 'Start / Attach' from the menu bar. You should be able to select '1up' and collide with wall and worm segments.
    Run

The next stage is to reset the game after the worm has died. Stage 6b >

Debugging

Your collision handling section should look like this:


	-- 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")
	elseif new_head_tile ~=15 then
		self.alive = false
		msg.post("main:/controller#main", "worm_died")
	end