Last active
April 19, 2021 18:23
-
-
Save theraot/cb5ffed23119a3086b07131566396c33 to your computer and use it in GitHub Desktop.
Draw loops with the mouse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node2D | |
class LoopCreator: | |
func is_type(type): return type == "LoopCreator" or .is_type(type) | |
func get_type(): return "LoopCreator" | |
signal loop(points_array) | |
var _points_array = PoolVector2Array() | |
func clear() -> void: | |
_points_array = PoolVector2Array() | |
func push(vector:Vector2) -> void: | |
if !_should_add(vector): | |
return | |
_points_array.append(vector) | |
if _points_array.size() > 25: | |
_points_array.remove(0) | |
if _points_array.size() > 3: | |
for index in range(0, _points_array.size() - 3): | |
if _segment_collision( | |
_points_array[-1], | |
_points_array[-2], | |
_points_array[index], | |
_points_array[index + 1] | |
): | |
loop(index) | |
break | |
func _should_add(vector:Vector2) -> bool: | |
return _points_array.size() == 0 or vector.distance_to(_points_array[-1]) > 20 | |
func _segment_collision(a1:Vector2, a2:Vector2, b1:Vector2, b2:Vector2) -> bool: | |
if sign(_wedge_product(a2 - a1, b1 - a1)) == sign(_wedge_product(a2 - a1, b2 - a1)): | |
return false | |
if sign(_wedge_product(b2 - b1, a1 - b1)) == sign(_wedge_product(b2 - b1, a2 - b1)): | |
return false | |
return true | |
func _wedge_product(a:Vector2, b:Vector2) -> float: | |
return a.x * b.y - a.y * b.x | |
func loop(index): | |
var array = Array(_points_array) | |
emit_signal("loop", PoolVector2Array(array.slice(index + 1, _points_array.size()))) | |
clear(); | |
onready var line:Line2D | |
onready var loop_creator:LoopCreator | |
func _ready(): | |
loop_creator = LoopCreator.new() | |
loop_creator.connect("loop", self, "_loop") | |
line = Line2D.new(); | |
add_child(line) | |
func _physics_process(_delta) -> void: | |
line.points = loop_creator._points_array | |
if Input.is_action_just_released("Left_click"): | |
loop_creator.clear() | |
elif Input.is_action_pressed("Left_click"): | |
var pos = get_global_mouse_position() | |
loop_creator.push(pos) | |
func _loop(loop:PoolVector2Array): | |
var polygon = Polygon2D.new() | |
var random_color = Color(randf(), randf(), randf()) | |
polygon.set_polygon(loop) | |
polygon.color = random_color | |
add_child(polygon) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment