go.property("speed", 100)

function init(self)
	-- msg.post(".", "acquire_input_focus")
	self.target_pos = vmath.vector3()
	self.state = "idling"
	self.next_state = "idling"
	self.selected = false
end

local function move_to_target(self, target, dt)
	local dist = target - go.get_position()
	if vmath.length_sqr(dist) < 50 then
		self.next_state = "idling"
	end
	local dir = vmath.normalize(dist)
	go.set_position(go.get_position() + dir * (self.speed * dt))
end

function update(self, dt)
	if self.state == "idling" and self.next_state == "moving" then
		sprite.play_flipbook("#sprite", "run")
		self.state = "moving"
	elseif self.state == "moving" and self.next_state == "idling" then
		sprite.play_flipbook("#sprite", "idle")
		self.state = "idling"
	end
	if self.state == "moving" then
		move_to_target(self, self.target_pos, dt)
	end
		
end

function on_message(self, message_id, message, sender)
	if message_id == hash("collision_response") then
		print(go.get_id())
	end
	if message_id == hash("trigger_response") then
		if message.enter then
			self.selected = true
		else
			self.selected = false
		end
	end
end

function final(self)
	-- Add finalization code here
	-- Learn more: https://defold.com/manuals/script/
	-- Remove this function if not needed
end

function on_reload(self)
	-- Add reload-handling code here
	-- Learn more: https://defold.com/manuals/hot-reload/
	-- Remove this function if not needed
end
