例如射击按钮,如果直接在update中判断btn()是否按下则会得到一个跟帧数相关的,射击频率。为了可以控制射击频率,并实现长按,这里使用一个time_since_press的变量,记录
--
function create_button(btn_num)
return
{
--上次按压后的时间
time_since_press=100,
--按键按下去的持续时间
time_held=0,
--按钮
button_number=btn_num,
button_init=function(b)
b.time_since_press,b.time_held=100,0
end,
button_update=function(b)
b.time_since_press+=one_frame
--当按键按下时开始记录按下持续时间和上次按下持续时间
if btn(b.button_number) then
if b.time_held==0 then
b.time_since_press=0
end
b.time_held+=one_frame
else
b.time_held=0
end
end,
--重新初始化按钮
button_consume=function(b)
b.time_since_press=100
end,
}
end
--
shoot_button=create_button(4)
dash_button=create_button(5)
shoot_button:button_init()
dash_button:button_init()
--如果按键按下去的时间不足0.2s,则将按钮的time_since_press设为100,即使按钮还没有抬起,依旧不会执行if中的语句,当再次按下按钮的时候time_since_press会被重置为0并触发if语句
if shoot_button.time_since_press<.2 or dash_button.time_since_press<.2 then
shoot_button:button_consume()
dash_button:button_consume()
end
--在_update中执行button_update
shoot_button:button_update()
dash_button:button_update()