Skip to content

Instantly share code, notes, and snippets.

@bitsycore
Last active September 26, 2021 20:27
Show Gist options
  • Save bitsycore/6214ef5cec2e411cbf7c8439f57f2ab1 to your computer and use it in GitHub Desktop.
Save bitsycore/6214ef5cec2e411cbf7c8439f57f2ab1 to your computer and use it in GitHub Desktop.
Show AABB of a Node2D
extends Node2D
export (NodePath) var node
onready var __node2d : Node2D = get_node(node)
func draw_aabb(points, color = Color(1.0, 0.0, 0.0)):
draw_rect(_points_to_aabb(points), color)
func _points_to_aabb(points):
var top_left = Vector2(-INF, -INF)
var bot_right = Vector2(INF, INF)
for point in points:
top_left.x = max(top_left.x, point.x)
top_left.y = max(top_left.y, point.y)
bot_right.x = min(bot_right.x, point.x)
bot_right.y = min(bot_right.y, point.y)
return Rect2(top_left, bot_right - top_left)
func _apply_transform_to_points(points : PoolVector2Array, transf : Transform2D):
# Vertex Transformed
for i in points.size():
points[i] = transf.xform(points[i])
return points
func _get_points_from_rect(rect):
var edited_rect = PoolVector2Array([
rect.position,
rect.position + Vector2(rect.size.x, 0),
rect.end,
rect.position + Vector2(0, rect.size.y)
])
return edited_rect
func _draw():
if __node2d is Sprite:
var pts = _get_points_from_rect(__node2d.get_rect())
pts = _apply_transform_to_points(pts, __node2d.transform)
draw_aabb(pts)
if __node2d is Polygon2D:
var pts = _apply_transform_to_points(__node2d.polygon, __node2d.transform)
draw_aabb(pts)
func _process(delta):
update()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment