hi, below is a part of my context-based steering script. it shoots i rays, and if it detects something in that direction, sets the corresponding index in the danger array to 5, if not, to 0.
What i would like it to do though is set the directions adjacent to the danger directions to 2. what i tried first was simply set the indexes i + 1 and i - 1 to 2, but that has two problems, first, if i set index 4+1 to 2, then next i’ll override it by setting index 5 to either 5 or 0. also when you try to access idex 0 - 1 or 8 + 1, the game crashes as those indexes dont exist. how would i go about doing this? basically what i need is for every index that doesnt detect a danger, but is adjacent to an index that detects danger, to be set to 2.
func set_danger():
var space_state = get_world_3d().direct_space_state
for i in num_rays:
var query = PhysicsRayQueryParameters3D.create(position, position + ray_directions[i] * look_ahead)
query.exclude = [self]
var result = space_state.intersect_ray(query)
if result:
danger[i] += 5.0
else:
danger[i] = 0
You could do a second loop this time looping over the danger array, to update the neighbours only if their value is not already 5 (same as being equal to zero)
var idx_num := 0
var change_value: Array[int] = []
for idx in danger_array:
If not idx == 5:
idx_num += 1
Continue
If danger_array[(idx_num - 1 + danger_array.size()) % danger_array.size()] != 5
change_value.append((idx_num - 1 + danger_array.size()) % danger_array.size())
If danger_array[(idx_num + 1) % danger_array.size()] != 5:
change_value.append((idx_num + 1) % danger_array.size())
idx_num += 1
for value in change_value:
danger_array[value] = 2
I edited this due to tshadows suggestions, just to make sure he has credit for the simplified code.
Also, I didnt know if your array had a fixed size, that is why why I used size(), but if it is fixed size you can just replace it with the size ie an array with max index of 7, the size would be 8.
you would use the modulus operator (usually: % or mod).
This gets the remainder of division.
So your array is 8 long, and you want to check index 7 neighbours.
You do (7+1) mod 8 = 1 with remainder zero. meaning 8 mod 8 = 0.