Problem number one: I want different layers to move at different speeds to create a parallax effect. Unfortunately, the solution I came up with doesn't work. Here are the relevant fragments of my code:
Code: Select all
-- variables for moving background
local layerOffsets = {}
local layerSpeeds = {
sky = 100,
ground = 150,
clouds = 50,
}
function love.load()
-- loading libraries
sti = require 'libraries/sti'
-- loading the background
map = sti('maps/robot_run_ext.lua')
-- Initialize offsets for each layer
for layer, _ in pairs(layerSpeeds) do
layerOffsets[layer] = 0
end
end
function love.update(dt)
-- Get the with of the map in pixels
local mapWidth = map.width * map.tilewidth
-- Update each layer separately
for layer, speed in pairs(layerSpeeds) do
layerOffsets[layer] = layerOffsets[layer] - speed * dt
-- Wrap around when the layer moves off-screen
if layerOffsets[layer] <= -mapWidth then
layerOffsets[layer] = 0
end
end
end
function love.draw()
local mapWidth = map.width * map.tilewidth
love.graphics.clear() -- Clear the screen
for layer, offset in pairs(layerOffsets) do
if map.layers[layer] then
map.layers[layer]:draw(offset, 0)
map.layers[layer]:draw(offset + mapWidth, 0)
end
end
end
Problem number two: The rendering of certain layers appears to be inconsistent and somewhat random. When I first launch the game, everything displays correctly (ground, sky, and clouds are all visible). However, if I close the game and restart it—without changing anything in the code—sometimes the clouds disappear, or parts of the ground aren't visible. Since those ground elements overlap with the sky, I suspect the sky is somehow being drawn on top of them.
The issue seems to be random: I can run the game five times in a row with everything displaying fine, and then on the next run, some elements suddenly disappear. Again, I don't change anything in the code between these launches.
I've checked that all my libraries are up to date, and everything appears to be in order. I expect the game to render layers consistently and allow them to move at different speeds as intended.
I atach my main.lua file to the post if you want to take a look.