Created
February 10, 2025 01:28
-
-
Save iamjoshellis/3828635e2c7be55adf65662d398e6913 to your computer and use it in GitHub Desktop.
Programatically Create CollisionPolygon2D based on AnimatedSprite2D
This file contains hidden or 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 CollisionPolygon2D | |
@export var animatedSprite2D: AnimatedSprite2D | |
# Programatically Create CollisionPolygon2D based on AnimatedSprite2D | |
func update_collision_polygon() -> void: | |
var data = ( | |
animatedSprite2D | |
. sprite_frames | |
. get_frame_texture(animatedSprite2D.animation, animatedSprite2D.frame) | |
. get_image() | |
) | |
var bitmap = BitMap.new() | |
bitmap.create_from_image_alpha(data) | |
var polys = bitmap.opaque_to_polygons(Rect2(Vector2.ZERO, Vector2(data.get_size())), 1) | |
for poly in polys: | |
polygon = poly | |
# Polygon needs to be centered | |
position = -Vector2(data.get_size()) / 2 | |
func _on_animated_sprite_2d_frame_changed(): | |
update_collision_polygon() | |
func _on_animated_sprite_2d_animation_changed(): | |
update_collision_polygon() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment