![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | AALivingMan |
Trying to dynamically generate CollisionPolygon2D
s for RigidBody2D
s based off a sprite. I was able to find this code for that which converts an Image
to a BitMap
based off the alpha values and converts it to an array of points that a CollisionPolygon2D
. This is what it looks like inside a Sprite2D
and updated a bit for Godot 4:
var bitmap: BitMap = BitMap.new()
bitmap.create_from_image_alpha(texture.get_image())
var polygons: Array[PackedVector2Array] = bitmap.opaque_to_polygons(Rect2i(Vector2.ZERO, texture.get_size()), 3.0)
# Set the first array from "polygons" as the CollisionPolygon2D's polygon
hitbox.polygon = polygons[0]
The problem though is that the RigidBodies behave super jankily with these dynamically generated hitboxes. They’ll flop around in a weird way and rotate around like they’re pivoted on one corner, the best way I can describe it is like the center of mass is off.
What’s weirder is that I exported these dynamically generated RigidBodies and when inspecting the polygon, it looks completely fine - just like the sprite. Some of them are even just a 4-point box because that’s what the sprite is yet they still behave weird.
Also, if I make a new CollisionPolygon2D
and manually make an outline, it behaves fine. But if I clear the polygons on the pre-existing dynamically made one, and then manually draw an outline, it has that same janky behavior…
And no, the issue isn’t that the Sprite/Hitbox is improperly centered.
Any clue why this is happening?