如何在Godot的_process函数中每隔1分钟调用扣币函数实现定时扣币?
实现Godot中每分钟扣除用户金币的功能
要实现每隔1分钟执行一次扣币操作,核心思路是跟踪上一次扣币的时间点,每次在_process函数中检查当前时间与上次扣币时间的差值是否达到60秒。以下是修改后的完整代码:
var game_started = false var time_start = 0 var time_now = 0 # 新增变量:记录上一次扣除金币的时间 var last_deduct_time = 0 func _process(delta): if game_started == true: time_now = OS.get_unix_time() # 检查是否已经过了1分钟(60秒) if time_now - last_deduct_time >= 60: # 执行扣币操作 deduct_one_coin_every_one_minute(uid) # 更新上次扣币时间为当前时间,保证下一次扣币间隔1分钟 last_deduct_time = time_now func start(pos): print("clicked start the game"); time_start = OS.get_unix_time() # 初始化上次扣币时间为游戏启动时间,确保第一次扣币在1分钟后触发 last_deduct_time = time_start set_process(true) game_started = true
关键说明:
last_deduct_time变量:专门用来存储上一次执行扣币操作的时间戳,避免重复触发或间隔不准确的问题- 时间差判断:通过
OS.get_unix_time()获取真实的系统时间戳,计算与上次扣币时间的差值,确保不管游戏帧率如何波动,都是按实际时间间隔执行扣币 - 初始化逻辑:在
start函数中同步初始化last_deduct_time,保证第一次扣币会在游戏启动后的第1分钟准时触发
注意:请确保uid参数在当前脚本中是可访问的(比如是全局变量、已传入的参数或从其他模块获取),否则需要补充对应的参数传递逻辑。
内容的提问来源于stack exchange,提问作者tree em
相关产品推荐
相关产品推荐

