【问题标题】:How to setup a custom save directory with Love2D如何使用 Love2D 设置自定义保存目录
【发布时间】:2022-09-24 20:51:48
【问题描述】:

我目前正在我的 Love2D 项目中使用love.graphics.captureScreenshot 方法,到目前为止一切顺利。我可以从wiki示例中看到...


function love.load()
    love.filesystem.setIdentity(\"screenshot_example\")
end

function love.keypressed(key)
    if key == \"c\" then
        love.graphics.captureScreenshot(os.time() .. \".png\")
    end
end

function love.draw()
    love.graphics.circle(\"fill\", 400, 300, 200)
end

...屏幕截图会自动保存到我的 Windows 10 目录中...

C:\\Users\\<user>\\AppData\\Roaming\\LOVE\\screenshot_example

但是我们如何设置自定义保存目录,这样我们可以更方便地保存这些资产的位置?

  • os.rename要搬家吗?

标签: love2d


【解决方案1】:

简短的回答,你不能使用 Löve API,但使用 Lua。

Löve2D 使用 PhysFS(对 IO 功能的抽象)来创建沙盒环境。这样,没有经验的程序员就不会在测试或执行期间意外删除整个硬盘驱动器或至少造成一些损坏。这意味着,在 Löves 启动时(在编译文件 boot.lua 内),设置可写和可读文件夹,以后不能取消设置。因此,到目前为止,Löve API 本身不允许将文件保存在预期的存储位置之外。

然而,Lua 本身提供标准的osio 功能,这些功能不通过 PhysFS。从那里你有几个选择:

通过 Löve2D 保存文件,然后通过os.rename 将其移动到所需文件夹或使用io.open 复制以读取文件并将其写入所需位置。

或者您可以直接使用io 将屏幕截图保存在所需位置。

无论哪种方式,您都可能遇到两个问题:

  • 如何创建文件夹
  • 如何找出用户文件夹的位置

请注意,以下代码仅适用于 Windows。如果这不是问题,请继续,如果你不想让它在 linux 下也能工作,你可能需要调整一些东西。

首先,Windows 将图片保存在C:\Users\<username>\Pictures 中。 我们将通过environment variable 访问用户配置文件文件夹。 然后我们需要创建一个folder,如果您希望将这些屏幕截图保存在子目录中。 旁注:我假设love.getIdentity 返回游戏名称。


local function mkdir(path)
    -- Notice we are using %q to allow for spaces (and prevent command injection)
    os.execute(string.format("mkdir %q", path)) -- System dependant
end

local function combinePaths(...)
    return (table.concat({...}, "\\"):gsub("\\+", "\\")) -- System dependant
end

local saveScreenshot

function love.load()
    love.filesystem.setIdentity("My Game")
    local screenshotDirectory = combinePaths(love.filesystem.getUserDirectory(), "Pictures", love.filesystem.getIdentity())
    mkdir(screenshotDirectory)
    function saveScreenshot()
        local fileName = os.date("%Y.%m.%d--%H-%M-%S")..".png"
        local filePath = combinePaths(love.filesystem.getSaveDirectory(), fileName)
        local destPath = combinePaths(screenshotDirectory, fileName)
        -- We are using a callback, because the screenshot is saved after draw() finishes executing
        ---@param image love.ImageData
        love.graphics.captureScreenshot(function(image)
            image:encode("png", fileName)
            os.rename(filePath, destPath)
        end)
    end
end

function love.keypressed(key)
    if key == "c" then
        saveScreenshot()
    end
end

function love.draw()
    love.graphics.circle("fill", 400, 300, 200)
end

【讨论】:

    猜你喜欢
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多