Now I'm trying to understand why this is happening. To my understanding the love.load() runs only once at the start up of the game. So why is there a difference to the 2 approaches?
Also what is the best place/way to instantiate new assets like images?
Code that jitters:
Uses local variables outside of the love.load() and then assigns the images inside the love.load() function to these variables.
Code: Select all
-- globals start
WIDTH = 512
HEIGHT = 288
-- globals end
local background
local ground
local pipe
local PIPE_WIDTH
local BACKGROUND_SCROLL_SPEED = 30
local GROUND_SCROLL_SPEED = 60
local BACKGROUND_LOOPING_POINT = 413
local backgroundX = 0
local groundX = 0
local pipeX = WIDTH
function love.load()
love.graphics.setDefaultFilter('nearest', 'nearest')
love.window.setMode(WIDTH * 2, HEIGHT * 2, {
vsync = 1
})
background = love.graphics.newImage('assets/background.png')
ground = love.graphics.newImage('assets/ground.png')
pipe = love.graphics.newImage('assets/pipe.png')
PIPE_WIDTH = pipe:getWidth()
end
function love.update(dt)
backgroundX = (backgroundX + BACKGROUND_SCROLL_SPEED * dt) % BACKGROUND_LOOPING_POINT
groundX = (groundX + GROUND_SCROLL_SPEED * dt) % WIDTH
pipeX = pipeX - GROUND_SCROLL_SPEED * dt
if (pipeX < -PIPE_WIDTH) then
pipeX = WIDTH
end
end
function love.draw()
love.graphics.push()
love.graphics.scale(2, 2)
love.graphics.draw(background, -backgroundX, 0)
love.graphics.draw(pipe, pipeX, HEIGHT / 2)
love.graphics.draw(ground, -groundX, HEIGHT-16)
love.graphics.pop()
end
Code that runs smooth:
Uses local variables outside of the love.load() and immediately assigns the images to these variables.
Code: Select all
-- globals start
WIDTH = 512
HEIGHT = 288
-- globals end
local background = love.graphics.newImage('assets/background.png')
local ground = love.graphics.newImage('assets/ground.png')
local pipe = love.graphics.newImage('assets/pipe.png')
local PIPE_WIDTH = pipe:getWidth()
local BACKGROUND_SCROLL_SPEED = 30
local GROUND_SCROLL_SPEED = 60
local BACKGROUND_LOOPING_POINT = 413
local backgroundX = 0
local groundX = 0
local pipeX = WIDTH
function love.load()
love.graphics.setDefaultFilter('nearest', 'nearest')
love.window.setMode(WIDTH * 2, HEIGHT * 2, {
vsync = 1
})
end
function love.update(dt)
backgroundX = (backgroundX + BACKGROUND_SCROLL_SPEED * dt) % BACKGROUND_LOOPING_POINT
groundX = (groundX + GROUND_SCROLL_SPEED * dt) % WIDTH
pipeX = pipeX - GROUND_SCROLL_SPEED * dt
if (pipeX < -PIPE_WIDTH) then
pipeX = WIDTH
end
end
function love.draw()
love.graphics.push()
love.graphics.scale(2, 2)
love.graphics.draw(background, -backgroundX, 0)
love.graphics.draw(pipe, pipeX, HEIGHT / 2)
love.graphics.draw(ground, -groundX, HEIGHT-16)
love.graphics.pop()
end
https://github.com/games50/fifty-bird/b ... ground.png
https://github.com/games50/fifty-bird/b ... 2/pipe.png
https://github.com/games50/fifty-bird/b ... ground.png