Spawn game object


Setup

spawn

The “carrotfactory” factory component uses the file carrot.go as prototype, meaning that it produces game objects that are all copies of that file.

carrot

Scripts

bunny.script

function init(self)
	msg.post(".", "acquire_input_focus") -- <1>
end

function on_input(self, action_id, action)
	if action_id == hash("touch") and action.pressed then -- <2>
		local pos = go.get_position()
		pos.x = pos.x + 100 -- <3>
		local carrot_id = factory.create("#carrotfactory", pos) -- <4>
		go.animate(carrot_id, "position.x", go.PLAYBACK_ONCE_FORWARD, 720, go.EASING_LINEAR, 3) -- <5>
	end
end

--[[
1. Acquire input focus so we get input from the engine.
2. If the user clicks.
3. Calculate a spawning position.
4. Tell the component "carrotfactory" ("#" denotes a component in the
   current game object) to spawn a game object according to its prototype.
   The function returns the id of the new game object.
5. Animate the position of the new game object.
--]]

carrot.script

function init(self)
	self.t = 2 -- <1>
end

function update(self, dt)
	self.t = self.t - dt -- <2>
	if self.t < 0 then
		go.delete() -- <3>
	end
end

--[[
1. Store a value `t` in the current script component (`self`).
2. Decrease `t` with delta time (elapsed since last call to `update()`).
3. If `t` is below 0, delete the current game object
   ("." is shorthand for that).
--]]

If you want to play with these examples, you can get the project on Github.

Do you want to see more examples? Why not write a few yourself and submit a pull request? We love contributions.

GITHUB