How to change background animation speed

Hi, i don't understand why my bg_speed doesn't work.
When i press KeyUP bg_speed var is incremented, so background animation should be accelerate.
need help.

#beginner

import "CoreLibs/sprites"
import "CoreLibs/animation"

-- performance shortcut

local gfx = playdate.graphics

local car_speed = 4
local bg_speed = 50

-- background sprite

local function CreateBackgroundSprite()

  local background = gfx.sprite.new()
background.imagetable = gfx.imagetable.new("images/outrun")

background:setBounds(0, 0, 400, 240)

background.animation = gfx.animation.loop.new(bg_speed, background.imagetable, true)

function background:update()

    self:setImage(self.animation:image())

end

background:add()
background:setZIndex(0)

end

local function CreatePLayer()
carSprite = gfx.image.new("images/car")
carSprite = gfx.sprite.new(carSprite)
carSprite:moveTo(160, 200)
carSprite:add()
end

CreateBackgroundSprite()
CreatePLayer()

function playdate.update()

gfx.setBackgroundColor(gfx.kColorBlack)

if playdate.buttonIsPressed(playdate.kButtonUp) then

    bg_speed = bg_speed - 1 -- background speed fast
    print(bg_speed)

end

if playdate.buttonIsPressed(playdate.kButtonDown) then

    bg_speed = bg_speed + 1 -- background speed slow

end

if playdate.buttonIsPressed(playdate.kButtonRight) then

    carSprite:moveBy(car_speed,0)

end

if playdate.buttonIsPressed(playdate.kButtonLeft) then

    carSprite:moveBy(-car_speed,0)

end

gfx.clear()
gfx.sprite.update()

end

thank you
playdate-20220503-114337

You set speed at the creation of the animation, with the value held in a variable.

After creation, changing the variable that holds the speed value is not enough, as it's not linked to the animation in any way. You'll need to change it on the animation directly.

Untested code:

if playdate.buttonIsPressed(playdate.kButtonDown) then

    bg_speed = bg_speed + 1 -- background speed slow

    background.animation.delay = bg_speed

end

thank you, i follow your advise.
i put background.animation.delay in background update function.
Now i need to find a solution to make the acceleration/deceleration effect smoother.
(Project test attached) :link:
Outestrun.zip (278.8 KB)

You would need to manage the bg_speed variable with some form of interpolation. So instead of setting to 1,2,3 etc directly, you would slowly increase by, say, 0.01 until it reaches your target speed.

See: playdate.math.lerp(min, max, t)
https://sdk.play.date/inside-playdate/#f-math.lerp

1 Like