Is it possible to implement function execution inside the update function?

I’m trying to implement a feature that the character is smoothly pushed backwards during a collision (i.e. the typical recoil after a blow), but so far nothing is working…

function update(self, dt)
	
	--Monster_move
	local pos = go.get_position()
	pos.x = pos.x - monster_stats.speed
	go.set_position(pos)

	function kickback()
		for i = 1, 10 do
			pos.x = pos.x + 1
			go.set_position(pos)
		end
	end
end

But the character just teleports, there is no smooth movement like when pos.x = pos.x + 1 in the body of the update function.

I call the kickback function itself when I receive a damage message.

This technically moves the player over time like you want, but since there’s no delay in the loop it’ll finish in just a fraction of a frame. That’s besides the point though because Defold already comes with the go.animate() function to change properties (like postion) over time:

local pos = go.get_position()
go.animate(
    ".", -- Refers to the object this script belongs to
    "position.x",
    go.PLAYBACK_ONCE_FORWARD, -- Do the animation once and then stop
    pos.x + 10,
    go.EASING_LINEAR, -- Move linearly without accelerating or decelerating
    1 -- Make the animation take 1 second to complete
)
4 Likes

Thank you very much ! I used this function in the tutorials but misunderstood its principle.

There’s also this example of using go.animate() for a knockback/recoil:

3 Likes