Godot引擎中布尔值异常反复切换问题求助
问题原因分析
你的has_battlemech值每帧在true/false间跳变,核心原因是多个战斗机甲实例(slot_1到slot_4)都在各自的_process帧更新函数中修改同一个全局player_city.stats["has_battlemech"]值:
- 当你购买了其中一个slot的机甲后,只有该slot的
has_it为true,其余slot的has_it仍为false - 每帧执行时,先由已购买的slot将
has_battlemech设为true,随后未购买的slot又会将其改回false,反复覆盖导致值来回跳
解决方案
方案1:直接在商店购买时修改全局状态(推荐)
去掉战斗机甲脚本里的_process同步逻辑,改为在商店点击购买时直接更新player_city的对应字段,避免多实例冲突:
修改商店的_on_Purchase_pressed函数:
func _on_Purchase_pressed(): if camera_in_first_spot: player_city.stats["has_battlemech"] = true slot_1.has_it = true # 保留slot自身状态用于显示等需求 if camera_in_second_spot: player_city.stats["has_ranged_battlemech"] = true slot_2.has_it = true if camera_in_third_spot: player_city.stats["has_helicopter"] = true slot_3.has_it = true # 第四个slot对应其他状态的话同理补充
同时删除战斗机甲脚本中的_process同步代码:
# 删除以下代码块 func _process(delta): print(player_city.stats["has_battlemech"]) if has_it: player_city.stats["has_battlemech"] = true if not has_it: player_city.stats["has_battlemech"] = false
方案2:统一全局状态判断逻辑(若需保留slot同步)
如果必须通过slot的has_it来同步全局状态,不要让每个slot单独覆盖,而是在一个全局管理器(比如PlayerCity单例)中统一判断所有slot的状态:
在PlayerCity单例中添加帧更新逻辑:
extends StaticBody var stats = { "has_battlemech": false, "has_ranged_battlemech": false, "has_helicopter": false } # 假设你能引用到所有slot实例 onready var slot_1 = $Path/To/Slot1 onready var slot_2 = $Path/To/Slot2 onready var slot_3 = $Path/To/Slot3 onready var slot_4 = $Path/To/Slot4 func _process(delta): # 只要对应slot的has_it为true,全局状态就设为true stats["has_battlemech"] = slot_1.has_it stats["has_ranged_battlemech"] = slot_2.has_it stats["has_helicopter"] = slot_3.has_it
同时删除各个slot脚本中的_process同步代码。
额外检查点
确认相机位置判断的camera_x值是精确匹配的(比如会不会因为相机移动的浮点精度问题,出现-29.999或0.001这类非精确值,导致所有camera_in_xxx都为false),可以给判断加个误差范围:
match round(camera_x): # 用round取整避免浮点精度问题 -30: camera_in_first_spot = true camera_in_second_spot = false camera_in_third_spot = false camera_in_fourth_spot = false 0: camera_in_first_spot = false camera_in_second_spot = true camera_in_third_spot = false camera_in_fourth_spot = false 30: camera_in_first_spot = false camera_in_second_spot = false camera_in_third_spot = true camera_in_fourth_spot = false 60: camera_in_first_spot = false camera_in_second_spot = false camera_in_third_spot = false camera_in_fourth_spot = true
内容的提问来源于stack exchange,提问作者AbsolutePickle42
相关产品推荐
相关产品推荐

