Function behave differant inside timer.delay()

I’m trying to move game object top to bottom using sprites dimensions, in normally it moves perfecly when i put inside a timer.delay() its go to differant position
what i want:

local backgrounds = {}
function init(self)
	local window_x, window_y = window.get_size()

	pos.x = window_x / 2
	pos.y = window_y / 2
	local bg = factory.create("#factory")
	go.set(bg, "position.y", window_y)
	go.set(bg, "position.x", window_x / 2)
	table.insert(backgrounds, bg)
	local url_sprite = msg.url(nil,"/instance"..#backgrounds-1, "sprite")
	go.animate(bg, "position.y", go.PLAYBACK_ONCE_FORWARD, -1*go.get(url_sprite, "size.y"), go.EASING_LINEAR, 2)
	timer.delay(3, true, function()
		go.delete(bg)
	end)
end

What i don’t want:

local backgrounds = {}
function init(self)
	local window_x, window_y = window.get_size()

	pos.x = window_x / 2
	pos.y = window_y / 2

	timer.delay(3, true, function()
		local bg = factory.create("#factory")
		go.set(bg, "position.y", window_y)
		go.set(bg, "position.x", window_x / 2)
		table.insert(backgrounds, bg)
		local url_sprite = msg.url(nil,"/instance"..#backgrounds-1, "sprite")
		go.animate(bg, "position.y", go.PLAYBACK_ONCE_FORWARD, -1*go.get(url_sprite, "size.y"), go.EASING_LINEAR, 2)
		timer.delay(3, true, function()
			go.delete(bg)
		end)
	end)
end

It seems like you want some kind of repeating background to move across the screen? It seems to me that it would be better to create the background sprites once and then move them across the screen and reset their positions when they leave the field of view.

There is an infinite runner with repeating ground sprites that move in the same way:

2 Likes

Thank you.
Very helpful.