raycast array

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By prosta4ock
:warning: Old Version Published before Godot 3 was released.

The problem with the Rays .
I get the output array that is sorted by id.

I need to get in the order in which they enter the ray.

Please help me.

Which code did you used? Raycasts return one element, not an array.

Zylann | 2016-07-27 23:18

var space_state = get_world_2d().get_direct_space_state()

var segment = SegmentShape2D.new()

segment.set_a(get_pos())
segment.set_b(get_pos() + line)

var query = Physics2DShapeQueryParameters.new()
query.set_shape(segment)
query.set_exclude([self]) 	
space_state.intersect_shape(query, 10)

prosta4ock | 2016-07-28 09:13

:bust_in_silhouette: Reply From: Zylann

Intersecting a segment will return unordered results because I guess it doesn’t usually matter, as well as shape intersection.
On the other hand, you can use a raycast, which will return the first encountered object.

If you really need all returned objects to be sorted by distance, you can put them in an array and sort them with whatever predicate you want:

# Note: using a class is not mandatory, you can also 
# use the script itself with `self` and a function,
# however I find it cleaner
class HitSorter:
	var origin = Vector2()
	func sort_hits(hit_a, hit_b):
		# Hmmm... no position in hits?
		return origin.distance(hit_a.collider.get_pos()) < origin.distance(hit_b.collider.get_pos())

func whatever():
	# ...
	
	var hits = space_state.intersect_shape(query, 10)
	var sorter = HitSorter.new()
	sorter.origin = segment.get_a()
	hits.sort_custom(sorter, "sort_hits")
	# Now they are ordered

However I also realize that the results of intersect_shape() don’t contain the position of the intersections, so I used hit.collider.get_pos(), which is less precise but should at least order the objects. This could be a good thing to ask on Github :stuck_out_tongue:

thanks for the help.
I solved the problem simply sorting the array.

prosta4ock | 2016-07-29 09:42