如何在 LUA(Love2d)中使一个函数等待 X 的时间?

我对编程非常陌生,来自于 SC2 等游戏的“自定义地图”背景。我目前正在尝试在 Love2d 中制作一个平台游戏。但是我想知道如何在进行下一件事之前等待 X 秒。

比如说我想让主角免疫 5 秒钟,那么代码应该是什么样的?

Immortal = true
????????????????
Immortal = false

据我所理解,Lua 和 Love2d 中没有内置的等待功能。

点赞
用户308010
用户308010

你可以这样做:

function delay_s(delay)
  delay = delay or 1
  local time_to = os.time() + delay
  while os.time() < time_to do end
end

然后你可以这样做:

Immortal == true
delay_s(5)
Immortal == false

当然,除非你在自己的线程中运行它,否则它会阻止你做任何其他事情。但是这只是我所知道的Lua,对Love2d我不熟悉,很遗憾。

2013-03-19 07:28:45
用户7625
用户7625

看起来你对于游戏元素的临时状态很感兴趣。这很常见——增益效果会持续六秒,敌人会被晕眩两秒,你的角色在跳跃时外观会发生改变等等。临时状态不同于等待,等待表示在你的五秒无敌期间绝对不会发生任何其他事情。看起来你想让游戏以正常方式继续,但是只有无敌时间为五秒的主角。

考虑使用“剩余时间”变量而不是布尔值来表示临时状态。例如:

local protagonist = {
    -- 这是无敌剩余时间,以秒为单位
    immortalityRemaining = 0,
    health = 100
}

-- 然后,想象一下在游戏中的某个地方获取了一个无敌增益效果。
-- 只需将immortalityRemaining设置为所需的无敌时间长度即可。
function protagonistGrabbedImmortalityPowerup()
    protagonist.immortalityRemaining = 5
end

-- 然后在每个love.update中减少一点剩余时间
-- 记住,dt是自上次更新以来经过的时间。
function love.update(dt)
    protagonist.immortalityRemaining = protagonist.immortalityRemaining - dt
end

-- 在计算对主角的伤害时,请考虑immortalityRemaining
function applyDamageToProtagonist(damage)
    if protagonist.immortalityRemaining <= 0 then
        protagonist.health = protagonist.health - damage
    end
end

谨慎处理“等待”和“计时器”等概念。它们通常是指管理线程。在一个具有许多运动部件的游戏中,通常更容易且更可预测地在不使用线程的情况下管理事物。如果绝对需要使用线程,则Löve在其love.thread模块中提供了线程功能。

2013-03-19 14:57:58
用户798888
用户798888

我通常使用 cron.lua 实现你所说的功能:https://github.com/kikito/cron.lua

Immortal = true
immortalTimer = cron.after(5, function()
  Immortal = false
end)

然后只需要在你的 love.update 中加入 immortalTimer:update(dt)

2013-05-08 18:21:19
用户6763451
用户6763451

我建议你在你的游戏中使用 hump.timer,像这样:

function love.load()
timer=require'hump.timer'
Immortal=true
timer.after(1,function()
Immortal=false
end)
end

而不是使用 timer.after,你也可以使用 timer.script,像这样:

function love.load
timer=require'hump.timer'
timer.script(function(wait)
Immortal=true
wait(5)
Immortal=false
end)
end

别忘了在 love.update 函数中添加 timer.update

function love.update(dt)
timer.update(dt)
end

希望能帮到你 ;)

下载链接:https://github.com/vrld/hump

2017-01-06 19:16:57