我很喜欢编程,并且来自像SC2这样的游戏中的“自定义地图”背景。我目前正在尝试在Love2d中制作平台游戏。但是我想知道在做下一件事之前我怎么能等待X秒。
说我想让主角不朽5秒,该代码怎么样?
Immortal = true
????????????????
Immortal = false
据我所知,Lua和Love2d没有内置等待。
听起来你对你的一个游戏实体的临时状态感兴趣。这是非常常见的 - 通电持续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
小心等待和计时器等概念。它们通常指管理线程。在具有许多移动部件的游戏中,在没有线程的情况下管理事物通常更容易且更可预测。在可能的情况下,将游戏视为巨型状态机,而不是在线程之间同步工作。如果线程是绝对必要的,Löve确实在它的love.thread模块中提供它们。
我通常使用cron.lua来讨论你所说的:https://github.com/kikito/cron.lua
Immortal = true
immortalTimer = cron.after(5, function()
Immortal = false
end)
然后在你的love.update中粘贴immortalTimer:update(dt)
。
你可以这样做:
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一无所知。
我建议您在游戏中使用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
别忘了添加timer.update
into功能love.update
!
function love.update(dt)
timer.update(dt)
end
希望这有帮助;)