I want to give the player the ability to draw their own Path2D by holding down lmb. The simple code below works, but it gives me the error _find_interval: Zero length interval which seems to be some leaky abstraction from C++, and I just want to know why I’m getting this error and how I could fix it.
extends CharacterBody2D
var path: Path2D
func _ready():
path = Path2D.new()
path.curve = Curve2D.new()
add_child(path)
func _process(delta):
if Input.is_action_pressed("click"):
path.curve.add_point(get_global_mouse_position())
This error occurs when the distance between the new point and the previous point is zero, so you can check whether the coordinates of the two points are the same beforehand:
extends CharacterBody2D
var path: Path2D
func _ready():
path = Path2D.new()
path.curve = Curve2D.new()
add_child(path)
func _process(delta):
if Input.is_action_pressed("click"):
var new_point = get_global_mouse_position()
if new_point != path.curve.get_point_position(-1):
path.curve.add_point(get_global_mouse_position())
Note: I haven’t tested this code, but I think it works fine, You can also merge bets and do it without creating variable:
if Input.is_action_pressed("click") and get_global_mouse_position() != path.curve.get_point_position(-1):
path.curve.add_point(get_global_mouse_position())
Both of the solutions give an index out of bounds error on my end. I’ve also tried using path.curve.get_baked_points().size()-1 instead of -1 as the index, but the issue persisted.
Instead, I opted for checking if the distance between the closest point in the path and new_point is 0.
I’ve also added a check if the point array in the curve is empty, so there wouldn’t be an error for calling get_closest_point() on an empty curve.
It looks a bit messy. I wonder if someone can find a more elegant solution.
func _process(delta):
if Input.is_action_pressed("click"):
var newPoint = get_global_mouse_position()
if path.curve.get_baked_points().size() == 0 \
or newPoint.distance_to(path.curve.get_closest_point(newPoint)) != 0:
path.curve.add_point(newPoint)