• 2D
  • How do I get the width of a sprite in another scene?

I have a scene that is Tile(Node2D) -> Body(RigidBody2D) -> Sprite(Sprite) -> CollisionShape2D(CollisionShape2D)

I have another scene. The attached gdscript references the sprite scene.

var tile = preload("res://Tile.tscn")

Before instantiation of a single tile, I want to know a tile's width. Something like this:

var width = tile.width

or

var width = tile.Body.Sprite.width

How can I get the width of an uninstantiated sprite?

You cannot really get the width of any node in Godot. But you can get the dimensions of the texture of the Sprite, and then you can multiply by the scale (if you have scaled it) to get the width height. To get a Node, you use get_node(). So you can do something like this:

var width = tile.get_node("Body/Sprite").texture.get_width()

But I'm on my laptop, I'm not sure if that code works, but it's something like that.

I get the error Invalid call. Nonexistent function 'get_node()' in base 'PackedScene.'

The variable "tile" is a PackedScene, which doesn't have a method get_node(). To use the PackedScene, you have to create an instance of it, which is a Node (in this case it's a Node2D, which is a subclass of Node).

Try this:

var tile: Node2D = preload("res://Tile.tscn").instance()
var width: int = tile.get_node("Body/Sprite").texture.get_width()
print_debug("The sprite's width is ", width)

I want to know the width of a tile ahead of adding an array of them to the scene. Is there a way to get the width of the sprite texture from the sprite node directly?

...though I suppose I'm thinking about this inside out and should be getting each tile's width as I add them.