2013-03-19 65 views
1

我对编程非常陌生,来自SC2等游戏中的“自定义地图”背景。我目前正在试图在Love2d上制作一款平台游戏。但我想知道如何在做下一件事之前等待几秒钟。如何使函数在LUA(Love2d)中等待X时间?

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

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

据我所了解,在Lua和Love2d中都没有建成等待。

+2

有一个 “休眠” 功能'love.timer.sleep(5)',但也许这是更好地切换'Immortal'在函数'love.update(dt)'里面的标志 – 2013-03-19 00:32:56

回答

-1

你可以这样做:

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一无所知。

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 

小心的概念,如等待定时器。他们通常指的是管理线程。在一个包含许多移动部件的游戏中,管理没有线程的东西通常更容易且更具可预测性。如果可能的话,把你的游戏看作一个巨大的状态机,而不是在线程之间同步工作。如果线程绝对必要,L ö ve确实在其love.thread模块中提供。

-1

我建议您在游戏中使用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添加到功能love.update

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

希望这有助于;)

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