Define correct.
There is code correctness and there is behavior correctness.
Behavior Correctness
This is subjective. i.e. If it doesn’t look or behave the way you want it to, then it isn’t correct.
Also, you haven’t described the whole sequence (bullet list would be good) of what a knockback should behave like.
Code Correctness
As far as the code… well it has a lot of assumptions so I don’t think it is great.
It assumes either there is only one enemy, or enemy is in scope, neither of which I think is guaranteed.
Better to make a function attached to the enemy itself when you make the enemy:
function enemy.knockback( self ) transition.cancel( self ) transition.to( self, {time=500,x=self.x-math.random(1,100),y=self.y-math.random(1,100),transition=easing.inOutBounce}) timer.performWithDelay(500, function() self:moveToPlayer() end ) end
Later called like this
enemy:knockback()
Your code also assumes the player is in scope. I can’t help on this. It totally depends on the structure of your game code.
Your timer.performDelay() call was wrong. You didn’t use a closure.
Request
I find one detail of your code posts really hard to deal with. You don’t use enough spaces.
Can you please start using spaces?
This makes double-click selecting code a pain in the butt and reading it a pain in the butt too.
This is bad:
transition.to(self,{time=500,x=self.x-math.random(1,100),y=self.y-math.random(1,100),transition=easing.inOutBounce})
This is better (more editable, and more legible):
transition.to( self, { time = 500, x = self.x - math.random( 1, 100 ), y = self.y - math.random(1,100), transition = easing.inOutBounce } )