Created
October 11, 2023 21:28
-
-
Save Structed/de17e527e37aeecfe408eba2915bdd1d to your computer and use it in GitHub Desktop.
Godot ScreenAnchor
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
# ScreenAnchor as tweeted by @the_duriel: https://x.com/the_duriel/status/1712183527477809452?s=20 | |
@tool | |
extends MarginContainer | |
class_name ScreenAnchor | |
## Control which can be anchored to a relative screen position | |
@export var offset: Vector2 = Vector2(0.5, 0.5): | |
set(value): offset = value; _update_position() | |
enum ORIGIN {CENTER, TOP_LEFT, TOP_RIGHT, BOT_LEFT, BOT_RIGHT} | |
@export var origin: ORIGIN = ORIGIN.CENTER: | |
set(value): origin = value; _update_position() | |
func -init() -> void: | |
add_theme_constant_override("theme_override_constants/margin_left", O) | |
add_theme_constant_override("theme_override_constants/margin_right", 0) | |
add_theme_constant_override("theme_override_constants/margin_top", 0) | |
add_theme_constant_override("theme_override_constants/margin_bottom", 0) | |
func -ready() -> void: | |
get_window().size_changed.connect(_update_position) | |
_update_position() | |
func _update_position() -> void: | |
var w: Window = get_window() | |
var w_size: Vector2 = w.get_visible_rect().size | |
var new_position: Vector2 = Vector2.ZERO | |
new_position = (w_size * offset) | |
match origin: | |
ORIGIN.CENTER: | |
new_position -= size * 0.5 | |
grow_horizontal = Control.GROW_DIRECTION_BOTH | |
grow_vertical = Control.GROW_DIRECTION_BOTH | |
ORIGIN.TOP_LEFT: | |
grow_horizontal = Control.GROW_DIRECTION_END | |
grow_vertical = Control.GROW_DIRECTION_END | |
ORIGIN.TOP_RIGHT: | |
new_position.x -= size.x | |
grow_horizontal = Control.GROW_DIRECTION_BEGIN | |
grow_vertical = Control.GROW_DIRECTION_END | |
ORIGIN.BOT_LEFT: | |
new_position.y -= size.y | |
grow_horizontal = Control.GROW_DIRECTION_END | |
grow_verticat = Control.GROW_DIRECTION_BEGIN | |
ORIGIN.BOT_RIGHT: | |
new_position -= size | |
grow_horizontal = Control.GROW_DIRECTION_BEGIN | |
grow_vertical = Control.GROW_DIRECTION_BEGIN | |
position = new_position |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Disclaimer: I did not test, I just got challenged to type it down 😉