Godot Version
v4.3.stable.official
Question
i tried to make [ make collisionPolygon2d to sprite fit pixel perfectly and automaticaly] with code.
ref:
code
extends Sprite2D
@onready var rigid = get_parent()
@onready var area = get_parent().get_node("Area2D")
var parent_level
var texture_source
var img_path
func make_collision2d() -> void:
area.connect('mouse_entered', Callable(self, '_on_mouse_entered'))
area.connect('mouse_exited', Callable(self, '_on_mouse_exited'))
var bitmap = BitMap.new()
bitmap.create_from_image_alpha(self.texture.get_image())
var polys = bitmap.opaque_to_polygons(Rect2(Vector2.ZERO, self.texture.get_size()), 0.5)
for poly in polys:
var collision_polygon1 = CollisionPolygon2D.new()
var collision_polygon2 = CollisionPolygon2D.new()
collision_polygon1.polygon = poly
collision_polygon2.polygon = poly
rigid.add_child(collision_polygon1)
area.add_child(collision_polygon2)
# Generated polygon will not take into account the half-width and half-height offset
# of the image when "centered" is on. So move it backwards by this amount so it lines up.
if centered:
#collision_polygon1.position = collision_polygon1.position - bitmap.get_size()/2
collision_polygon1.position.x = collision_polygon1.position.x - bitmap.get_size().x/2
collision_polygon1.position.y = collision_polygon1.position.y - bitmap.get_size().y/2
collision_polygon2.position.x = collision_polygon2.position.x - bitmap.get_size().x/2
collision_polygon2.position.y = collision_polygon2.position.y - bitmap.get_size().y/2
func _on_mouse_entered() -> void:
modulate = Color.RED
func _on_mouse_exited() -> void:
modulate = Color.WHITE
func _on_ball_ball_parent_done(parent_level) -> void:
self.parent_level = parent_level
print(parent_level)
img_path = "res://assets/img/relics_img/"+ str(parent_level) +".png"
texture_source = load(img_path)
self.texture = texture_source
self.scale = Vector2(4, 4)
self.position = Vector2(0, 0)
self.centered = true
make_collision2d()
problems
- collision size is smaller then i expect
i scale up sprite(1 → 4)
and i think
bitmap.create_from_image_alpha(self.texture.get_image())
this line doesn’t considering that.
so i tried to change other line to
var polys = bitmap.opaque_to_polygons(Rect2(Vector2.ZERO, self.texture.get_size() ***4**), 0.5)
but is not worked
how can i collision scale up to fit sprite
- gravity movement is weird
click → fall → collision makes stop themselve
collision work but every items(instanced) standing up
specific info
i think ref sources are old version so i should’ve change some lines(i’m not sure those problems from that)
collision_polygon1.position.x = collision_polygon1.position.x - bitmap.get_size().x/2
original node path
ball (rigidbody2d)
|- ball_sprite2d
|- Area2d
after script run
ball (rigidbody2d)
|-@collisionPolygon2d(same shape, same add_childed)
|- ball_sprite2d
|- Area2d
|-@collisionPolygon2d(same shape, same add_childed)