Different variables from an Array

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By javrocks

Hi i have an array of vectors and a choose function() that selects a vector from the array. The problem is sometimes it chooses the same vector twice and so the KinematicBody2D overlaps when the scene is instanced. I need it to choose a different Vector each time, so that the previous global position and the current global position aren’t the same. How do i do this?

extends KinematicBody2D


func _ready():
  global_position = choose([Vector2(626,904),Vector2(1474,846),Vector2(1518,356),Vector2(1506,-96)])
func choose(array):
   array.shuffle()
   return array.front()
:bust_in_silhouette: Reply From: SnapCracklins

What I would do is use

array.pop_front()

to remove a value, then you won’t select it again. Then just run a function if the array is empty to refill it.
Like add:

var default_array = ### insert your original vector values here

And then in wherever this function is triggered:

if array.empty() = true:
   array = default_array

This is what i have now. When instance a few of them, the body’s still overlap

extends KinematicBody2D

var default_array = ([Vector2(626,904),Vector2(1474,846),Vector2(1518,356),Vector2(1506,-96)])

func _ready():
  global_position = choose([Vector2(626,904),Vector2(1474,846),Vector2(1518,356),Vector2(1506,-96)])
func choose(array):
  if array.empty() == true:
	  array = default_array
  array.shuffle()
  return array.pop_front()

javrocks | 2022-09-04 20:48