godot-steering-ai-framework/project/demos/FollowPath/Drawer.gd

56 lines
1.4 KiB
GDScript3
Raw Normal View History

2020-01-15 20:42:24 +01:00
extends Node2D
signal path_established(points)
var active_points := []
var is_drawing := false
var distance_threshold := 100.0
2020-01-15 20:42:24 +01:00
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventMouseMotion:
if is_drawing:
2020-01-15 20:42:24 +01:00
active_points.append(event.position)
update()
elif event is InputEventMouseButton:
if event.pressed and event.button_index == BUTTON_LEFT:
active_points.clear()
active_points.append(event.position)
is_drawing = true
2020-01-15 20:42:24 +01:00
update()
elif not event.pressed:
is_drawing = false
2020-01-16 17:08:23 +01:00
if active_points.size() >= 2:
_simplify()
2020-01-15 20:42:24 +01:00
func _draw() -> void:
if is_drawing:
2020-01-15 20:42:24 +01:00
for point in active_points:
draw_circle(point, 1, Color.red)
else:
if active_points.size() > 0:
draw_circle(active_points.front(), 2, Color.red)
draw_circle(active_points.back(), 2, Color.yellow)
draw_polyline(active_points, Color.skyblue, 1.0)
2020-01-15 20:42:24 +01:00
func _simplify() -> void:
var first: Vector2 = active_points.front()
var last: Vector2 = active_points.back()
var key := first
var simplified_path := [first]
2020-01-15 20:42:24 +01:00
for i in range(1, active_points.size()):
var point: Vector2 = active_points[i]
var distance := point.distance_to(key)
2020-01-15 20:42:24 +01:00
if distance > distance_threshold:
key = point
simplified_path.append(key)
active_points = simplified_path
if active_points.back() != last:
active_points.append(last)
update()
emit_signal("path_established", active_points)