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

1 lua timer wait love2d

我很喜欢编程,并且来自像SC2这样的游戏中的"自定义地图"背景.我目前正在尝试在Love2d中制作平台游戏.但是我想知道在做下一件事之前我怎么能等待X秒.

说我想让主角不朽5秒,该代码怎么样?

Immortal = true 
????????????????
Immortal = false
Run Code Online (Sandbox Code Playgroud)

据我所知,Lua和Love2d没有内置等待.

Cor*_*rch 8

听起来你对你的一个游戏实体的临时状态感兴趣.这是非常常见的 - 通电持续6秒,敌人被击晕2秒,你的角色在跳跃时看起来不同等等.临时状态与等待不同.等待表明,在你的五秒不朽期间绝对没有其他事情发生.听起来你希望游戏能够像往常一样继续游戏,但是拥有一个不朽的主角五秒钟.

考虑使用"剩余时间"变量与布尔值来表示临时状态.例如:

local protagonist = {
    -- This is the amount of immortality remaining, in seconds
    immortalityRemaining = 0,
    health = 100
}

-- Then, imagine grabbing an immortality powerup somewhere in the game.
-- Simply set immortalityRemaining to the desired length of immortality.
function protagonistGrabbedImmortalityPowerup()
    protagonist.immortalityRemaining = 5
end

-- You then shave off a little bit of the remaining time during each love.update
-- Remember, dt is the time passed since the last update.
function love.update(dt)
    protagonist.immortalityRemaining = protagonist.immortalityRemaining - dt
end

-- When resolving damage to your protagonist, consider immortalityRemaining
function applyDamageToProtagonist(damage)
    if protagonist.immortalityRemaining <= 0 then
        protagonist.health = protagonist.health - damage
    end
end
Run Code Online (Sandbox Code Playgroud)

小心等待计时器概念.它们通常指管理线程.在具有许多移动部件的游戏中,在没有线程的情况下管理事物通常更容易且更可预测.在可能的情况下,将游戏视为巨型状态机,而不是在线程之间同步工作.如果线程是绝对必要的,Löve确实在它的love.thread模块中提供它们.