This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

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?

in Engine by (15 points)

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 (https://github.com/godotengine/godot/issues) and see what they say there

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

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

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

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...

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.