Skip to content

Instantly share code, notes, and snippets.

@stepheng
Last active August 12, 2023 21:09
Show Gist options
  • Save stepheng/c8b4e1f28e903712842af3e6d89289e0 to your computer and use it in GitHub Desktop.
Save stepheng/c8b4e1f28e903712842af3e6d89289e0 to your computer and use it in GitHub Desktop.
Sierpinski Triangle - Godot
extends Node2D
#var axiom = "F++F++F++"
var axiom = "A"
var angle_step = deg_to_rad(60)
var iteration = 1
var step_length: float = 64
var frame = Rect2(0, 0, 0, 0)
var rules = {
"F": "F-F++F-F",
"A": "B-A-B",
"B": "A+B+A"
}
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
func _draw():
var start_x = 0 if iteration % 2 == 1 else (get_window().size.x * (1 / scale.y))
var start_y = (get_window().size.y) * (1 / scale.y)
var position = Vector2(start_x, start_y)
var angle = deg_to_rad(90) if iteration % 2 == 1 else deg_to_rad(270)
var current = LNode.new(angle, position)
for command in axiom:
match(command):
"F", "A", "B":
var delta = Vector2.UP.rotated(current.angle) * step_length
var end_point = current.position + delta
draw_line(current.position, end_point, Color.GREEN, 1.0 / scale.x, true)
current.position = end_point
"+":
current.angle -= angle_step
"-":
current.angle += angle_step
frame.size.x = max(current.position.x - start_x, frame.size.x)
frame.size.y = max(current.position.y - start_y, frame.size.y)
frame.position.x = min(current.position.x - start_x, frame.position.x)
frame.position.x = min(current.position.y - start_y, frame.position.y)
func _on_button_pressed():
iteration += 1
var new_axiom = ""
for command in axiom:
var rule = rules.get(command, command)
new_axiom += rule
axiom = new_axiom
queue_redraw()
func _on_shrink_pressed():
scale *= 0.75
queue_redraw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment