Changing CollisionShape2D size for Different Instances

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

I’m working on a 2D game and wanted a general class for items on the map:

extends StaticBody2D

var file2Check = File.new()

func initialize(location=Vector2.ZERO, spriteName="cactus"):
	position = location
	var spritePath = "res://assets/platformer-art-deluxe/Base pack/Items/" + spriteName + ".png"
	#verify image existence
	if !file2Check.file_exists(spritePath):
		spritePath = "res://icon.png"
	#set sprite image
	var spriteTexture = load(spritePath)
	get_node("Sprite").set_texture(spriteTexture)
	#adjust collision rectangle size
	var spriteSize = spriteTexture.get_size()
	get_node("CollisionShape2D").get_shape().set_extents(spriteSize)

On a different script (for the level’s scene), I wish to instantiate 2 items - each has its own image with its own size:

extends TileMap

var items = preload("res://src/items/item.tscn")

func _ready() -> void:
	var shiny = items.instance()
	shiny.initialize(Vector2(300,0), "gem_green")
	add_child(shiny)
	var cactus = items.instance()
	cactus.initialize(Vector2(-150,180))
	add_child(cactus)

My problem: both items are assigned the size of the latter sprite, the cactus (in term of collision shape). I figured my code overrides my class, but I just want to configure the instances. Is that possible?

Unless I’m totally misunderstanding how this is supposed to work in godot, this seems like it might be a bug. I would create an issue on github (Issues · godotengine/godot · GitHub) and see what they say there

Eric Ellingson | 2020-03-12 00:23

I’m a newbie to Godot so I thought it’s probably my misunderstanding. Thanks

saoded | 2020-03-12 06:34

You should not use CollisionsShape2D from code. It is just a helper node for editor.

See the answer here: https://forum.godotengine.org/12876/changing-radius-collision-shape-makes-collision-shapes-change

RedPilled | 2020-03-12 09:15

As an alternative to the mentioned thread, if you only require a handful of different collision shape sizes, you could simply include them all in the original scene, but set them to disabled.

Then, once you’ve created an instance, enable the collision shape you need based on its sprite…

jgodfrey | 2020-03-12 14:25