最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

game development - Layers display and movement in Love2D (Lua) - Stack Overflow

programmeradmin5浏览0评论

I'm currently working on a small 2D game using the LÖVE2D engine. I created a background with Tiled and exported it as a .lua file. However, I'm facing two issues with this background:

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:

-- 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

When I launch the game, nothing moves, and I have no idea why. Previously, I tried moving the entire background as a single entity (without separating layers), and everything worked smoothly.

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.

发布评论

评论列表(0)

  1. 暂无评论