How to move a sprite?

Hello everyone, I’m new to Defold
I’m making my first game and would like to do a sort of intro
After 3sec, the title appears, and after 1 seconds, it move sup
the problem is, after the 1 second waiting, I have this probleme

ERROR:SCRIPT: main/Title script.script:15: attempt to perform arithmetic on field 'pos' (a nil value)
stack traceback:
  main/Title script.script:15: in function <main/Title script.script:13>

here is my script:

function init(self)
	sprite.set_constant("/FishyJourney", "tint", vmath.vector4(1, 1, 1, 0))
	local pos = vmath.vector3()
end

function final(self)

end

function update(self, dt)
	timer.delay(3, false, function()
		sprite.set_constant("/FishyJourney", "tint", vmath.vector4(1, 1, 1, 1))
		timer.delay(1, false, function()
			for i=1, 20 do
				self.pos = self.pos + 10
			end
		end)
	end)
end

This tells you that on line 15 you try to perform a math operation on a field that doesn’t exist (it is nil).

Here’s why this happens:

You define pos as a local variable in init():

And in update() you try to use self.pos, ie a variable stored on the self object:

Solution? Change to self.pos = vmath.vector3() in init!

Welcome to defold!

Britzl is right. If you’re just getting started, a good habit would be to use self.name for your variables. e.g self.pos, self.size, self.health. That means all your variables are available to the whole script. There are also local variables and global variables, but you can learn about those later.

1 Like

I can already see the next trouble you’re going to run into here… the “update” function runs around 60 times a second. You should put all this code in your init, as follows:

function init(self)
	sprite.set_constant("/FishyJourney", "tint", vmath.vector4(1, 1, 1, 0))
	local pos = vmath.vector3()
	timer.delay(1, false, function() 
		sprite.set_constant("/FishyJourney", "tint", vmath.vector4(1, 1, 1, 1))
		timer.delay(1, false, function()
			for i=1, 20 do
				self.pos = self.pos + 10
			end
		end)
	end)
end

another option would be to use go.animate:

function init(self)
	sprite.set_constant("/FishyJourney", "tint", vmath.vector4(1, 1, 1, 0))
	timer.delay(1, false, function() 
		sprite.set_constant("/FishyJourney", "tint", vmath.vector4(1, 1, 1, 1))
	end)
go.animate(".", "position.y", go.PLAYBACK_ONCE_FORWARD, 1200, go.EASING_OUTSINE, 2, 1)
end

that will automatically animate the y position of the game object to 1200 using a nice sine wave easing. The animation will take 2 seconds, and it happen after a one second delay.

3 Likes

Thank you all for your answers !
Hope you’ll have a nice day :slight_smile: