Frame al secondo

Quanto basta?

Più veloce non è sempre meglio

Quanto basta?

Il tipo di gioco che sto per fare non ha bisogno di molti FPS. Ma torniamo all’inizio: che cos’è? È il numero di frame (immagini sullo schermo) mostrati uno dopo l’altro in 1 secondo.

Se dici 30 FPS, mostri 30 immagini una dopo l’altra in 1 secondo. Se gli FPS sono troppo pochi vedi immagini a scatti, non fluide (non è sempre così).

Al momento il mio obiettivo è usare almeno 60 FPS e, come vedi, è proprio così 😄

FPS nel gioco

FPS nel gioco

Mantenere il controllo

Ho letto diversi articoli su cosa sia meglio e più semplice. Dipende dal tipo di gioco e dalla piattaforma. Visto che punto sull’affidabilità e che si tratta di un semplice gioco 2D, ho scelto di fissare il framerate a 60.

Per questo uso https://github.com/bjornbytes/tick con in più una mia modifica, così che al momento è così.

local tick = {
  rate = 1 / 60
}

local timeAccumulator = 0

function love.run()
  love.load(love.arg.parseGameArguments(arg), arg)
  love.update(0)
  love.timer.step()

  return function()
    -- Handle events.
    love.event.pump()
    for name, a, b, c, d, e, f in love.event.poll() do
      if name == "quit" and not (love.quit and love.quit()) then
        return a or 0
      end
      love.handlers[name](a, b, c, d, e, f)
    end

    -- Get delta time.
    local _, _, flags = love.window.getMode()
    local dt = love.timer.step()

    if flags.vsync > 0 and flags.refreshrate > 0 then
      local perfectDt = 1 / flags.refreshrate

      if dt < perfectDt * 1.3 and dt > perfectDt / 1.3 then -- If dt is somewhat near perfect, force it to be actually perfect.
        dt = perfectDt
      else
        dt = math.min(dt, 1 / 20) -- In case the game is lagging, let it lag (but let the game think it's at least 20 FPS). Not clamping dt may put us in a situation where we can't do all required ticks in time and the game will more or less freeze.
      end
    end

    -- Update game.
    timeAccumulator = timeAccumulator + dt
    local didUpdate = false

    while timeAccumulator >= tick.rate do
      timeAccumulator = timeAccumulator - tick.rate
      didUpdate = true

      -- local updateStartTime = love.timer.getTime()
      love.update(tick.rate)
      -- love.timer.sleep(20*(love.timer.getTime()-updateStartTime)) -- DEBUG: Emulate a slower computer.
    end

    -- Draw game.
    if didUpdate then
      love.graphics.origin()
      love.graphics.clear(love.graphics.getBackgroundColor())
      love.draw()
      love.graphics.present()
    end

    if not (flags.vsync > 0 and didUpdate) then
      love.timer.sleep(.001) -- Not needed if vsync is on and we called present(), as present() will have slept for us.
    end
  end
end

Lo faccio per poter dare per scontato che funzioni sempre a 60 FPS e che non succedano cose strane se qualcuno ha una scheda video che arriva a 10000 FPS. Con questa tecnica resta ‘sempre’ stabile.

Deltatime

In quasi tutto ciò che si muove uso il deltatime per evitare che i movimenti vadano fuori sincrono.

---Move point to destination
---@param dt number DeltaTime
---@return integer? x,integer? y,boolean? stopped
function Move:updateToDestination(dt)
    if self.vDestination == nil then
        return
    end

    local dist = self.vPosition:dist(self.vDestination)
    local step = self.speed * dt

Vsync

La maggior parte dei monitor ha anche l’opzione vsync, che in ogni caso ho attivato in Love2d.

t.window.vsync = 1 -- Vertical sync mode (number)

Per finire

Non so ancora al 100% se quello che ho pensato qui corrisponde alla pratica. Lo scoprirò solo dopo aver fatto qualche test su diversi computer e dispositivi. Credo che non lo avrai mai perfetto per tutti i sistemi. Ci sono ovviamente anche computer troppo lenti, su cui il gioco non funziona al meglio. Al momento sto sperimentando per mostrare un avviso in quei casi.

    local checkFpsSeconds = .1
    local minimalFpsNeeded = 55
    local warningAfterSeconds = 4.0
    local startLoadingTime = love.timer.getTime()
    self.tick =
        Tick.recur(
        function()
            local fps = love.timer.getFPS()

            if tonumber(love.timer.getTime() - startLoadingTime) > warningAfterSeconds then
                loadingScreen.textObj:setText("You need " .. tostring(minimalFpsNeeded - fps) .. " FPS more.")
            end

            if fps > minimalFpsNeeded then
                self.tick:stop()

                -- everything is fast
            end
        end,
        checkFpsSeconds
    )