RigidBody2D with dynamically generated CollisionPolygon2D behaves strangely

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By AALivingMan

Trying to dynamically generate CollisionPolygon2Ds for RigidBody2Ds 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?

:bust_in_silhouette: Reply From: AALivingMan

I managed to fix it! It turns out my issue was sort of related to a line of code related to centering that I neglected to include thinking it wasn’t the problem.
I compared one of the generated polygons with a manually made recreation and noticed their values was off. To make my CollisionPolygon2D work with centered sprites all I did originally was

hitbox.position -= Vector2(texture.get_size() / 2)

This however, didn’t seem to actually help with the wrong values but made it look right to me.
The proper way to fix the offset for centered sprites is to add this before setting the polygons on the CollisionPolygon2D:

for i in polygons[0].size():
	# Offset the value on each point since sprite is centered
	polygons[0].set(i, polygons[0][i] - Vector2(texture.get_size() / 2))