Worm | Growing the worm.

When food is eaten the worm grows by one segment. The easiest way to achieve this is to only remove the tail if the grow attribute is false.

  1. In the assets panel, in the 'main' folder, double click, 'worm1.script'.
  2. Change the update function to call the remove_tail(self) and create_new_tail(self) functions only if grow is false. The code presented here is the fully updated function so you can simply over-write the code you already have for this entire function.

function update(self, dt)
	-- Only update on timer alarm
	self.timer = self.timer + dt
	if self.timer >= 1 / self.speed then
		self.timer = 0
		-- If the worm is alive, update its position
		if self.alive then
			process_inputs(self)
			change_head_into_body(self)
			create_new_head(self)
			-- Don't remove tail if worm is growing, increase the speed
			if self.grow then 
				self.speed = self.speed + 0.5
				self.grow = false
			elseif self.alive then
			-- If worm is not growing, remove the tail
				remove_tail(self)
				create_new_tail(self)
			end
		end
	end
end
What does this code do?

The new section of code is:

if self.grow then
self.speed = self.speed + 0.5
self.grow = false
elseif self.alive then
remove_tail(self)
create_new_tail(self)
end

This increases the speed and resets the grow flag if the worm is growing.

Otherwise it removes the tail and creates a new one if the worm is still alive.

The additional condition to check the worm is still alive prevents the head eating the tail when the worm dies.

  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 collect apples. The worm will grow when an apple is eaten.
    Run

The next stage is to add the collision handling for all the other game objects except the food. Stage 6a >