Godot 4中使用pick_random选取坐标数组时如何避免重复?
避免重复选取坐标的解决方案
方案1:维护可用坐标池
单独维护一个可用坐标数组,每次从里面随机选取后移除该坐标,当可用坐标为空时再重置回原始的points数组,适合需要彻底避免重复直到一轮选完的场景。
修改后的代码(同时修正了你原代码中add_child的错误):
# 成员变量:存储当前可选取的坐标 var available_points: Array[Vector2] = [] func _ready() -> void: # 初始化可用坐标池为原始points的副本 available_points = points.duplicate() func _process(delta: float) -> void: if item_destroyed == true: # 可用坐标为空时,重置回原始坐标集合 if available_points.is_empty(): available_points = points.duplicate() var the_item = item.instantiate() add_child(the_item) # 随机选取坐标并从可用池移除 var selected_point = available_points.pick_random() available_points.erase(selected_point) the_item.position = selected_point item_destroyed = false print(item_destroyed)
方案2:记录已使用坐标,选取时跳过
用集合记录已使用的坐标,每次随机选取后检查是否已被使用,直到找到未使用的坐标。当所有坐标都用过一轮后清空记录集合,适合不想修改原始数组结构的场景。
代码示例:
# 成员变量:记录已使用的坐标 var used_points: Set[Vector2] = {} func _process(delta: float) -> void: if item_destroyed == true: # 所有坐标都使用过一轮后,重置记录 if used_points.size() == points.size(): used_points.clear() var selected_point: Vector2 # 循环选取直到找到未使用的坐标 repeat: selected_point = points.pick_random() until not used_points.has(selected_point) used_points.add(selected_point) var the_item = item.instantiate() add_child(the_item) the_item.position = selected_point item_destroyed = false print(item_destroyed)
方案3:打乱数组顺序后依次选取
先打乱points数组的顺序,然后按顺序逐个选取,遍历完所有坐标后重新打乱,适合需要随机遍历而非完全随机选取的场景(避免短时间内重复选取的同时,保证一轮内每个坐标只出现一次)。
代码示例:
# 成员变量:存储打乱后的坐标数组和当前选取索引 var shuffled_points: Array[Vector2] = [] var current_index: int = 0 func _ready() -> void: # 初始化时打乱坐标数组 shuffled_points = points.duplicate() shuffled_points.shuffle() func _process(delta: float) -> void: if item_destroyed == true: # 遍历完所有坐标后,重新打乱并重置索引 if current_index >= shuffled_points.size(): shuffled_points.shuffle() current_index = 0 var the_item = item.instantiate() add_child(the_item) the_item.position = shuffled_points[current_index] current_index += 1 item_destroyed = false print(item_destroyed)
内容的提问来源于stack exchange,提问作者Diego Sandoval
相关产品推荐
相关产品推荐

