Using performAfterDelay to delay an object from performing an action

,

I am attempting to create an enemy in a game that shoots a bullet every 5 seconds.
I'm currently using the performAfterDelay function in the timer library to delay the shoot function.

function enemy:shoot(x, y)
    local projectileInstance = bullets(x, y, "images/squareBullets", 2, "square")
    projectileInstance:add()
end

function enemy:ability()
    local function timerCallback()
        self:shoot(self.x, self.y)
    end
    pd.timer.performAfterDelay(5000, timerCallback)
    --pd.timer.performAfterDelay(50, timerCallback)
end

function enemy:update()
    enemy.super.update(self) --overrride default update

    self:ability()
    pd.timer.updateTimers()
    gfx.sprite.update()
end

However, multiple bullets show up on screen instead one every 5 seconds.

playdate-20220612-185223

I think this happens because the performAfterDelay function execute the shoot function slower than the playdate update function executes.
I guess my question is: how do I decrease the rate at which new bullet sprites are created?

Without the rest of your code for context, I'd recommend using a timer or a frameTimer for this. It would be pretty straightforward to create one new bullet sprite every 30 frames, for example.

1 Like

The issue is you're calling self:ability() on every update, this is setting up a new timer every update! It fits with what you're seeing, an initial delay then an endless stream.

If you want to repeat an action every 5 second the easiest way probably is to create a timer in the enemy's init method and set timer.repeats to true

1 Like