How to detect when a Line2D crosses itself ?

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

Hello,

I am pretty new to Godot and to programming (and I’m in love with this engine !)
After learning how to make a plateformes and the basics, I tried making a game
where an object follows the mouse and create a trail. The thing is that I want to detect when the trail crosses itself (here is an exemple), and if an object is inside the area it created. (Here is an image explaining all of this : Screenshot-Game hosted at ImgBB — ImgBB)

Thank you :slight_smile:

Script of my line2D :

   extends Line2D

onready var point
onready var trail_length = 50

func _process(delta):
	
	set_as_toplevel(true)
	
	point = get_parent().get_parent().global_position
	add_point(point)
	while (get_point_count() > trail_length):
		remove_point(0)
		pass
	

Script of my player

extends KinematicBody2D

var velocity = Vector2()
var speed = 5

func _process(delta):
	
	var mouse_pos = get_viewport().get_mouse_position()
	var player_pos = get_position()

	velocity = (mouse_pos - player_pos) * speed
	
	move_and_slide(velocity, Vector2(0, -1))
:bust_in_silhouette: Reply From: jgodfrey

You’re image is broken, but I think I understand what you’re trying to do. I don’t think there’s a magic-bullet for what you want, but I’d guess you could build it fairly easily using some of Godot’s basic Geometry functions. For instance, these will likely be handy:

segment_intersects_segment_2d - find intersection between 2 line segments
is_point_in_polygon - determine if a point is inside a polygon

Basically, you’ll need to see if your “line segments” have any intersections (by iterating through the segments and comparing them via segment_intersects_segment_2d). If they don’t, you’re done. If you find an intersection, you’ll need to create a collection of points consisting of that intersection point and all of the points “between” the 2 segments found to have the intersection (including the last point of the first intersecting segment and the first point of the second intersecting segment) - in that order.

That list of points could be used to construct a “containing” polygon - which could be used to find objects “inside” using any number of methods (potentially including is_point_in_polygon).