How can I get the size of sprites?

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

As I can see, many people have asked this question here, but the answers aren’t work in my code, because it doesn’t know “texture” property.
I would like set the position of the enemy objects based on their sprites. E.g. let an enemy be created at -128 and (get_viewport_rect().size).y-256 if it has 128*256 pixels dimensions. So, let it be outside the screen, at its left corner.
I tried texture.get_size() and similar commands, but it never liked “texture” property.
Here is my piece of code:

func _startenemy():
var eninst=preload("res://monster1.tscn")
var itssprite: Sprite=get_node("res://monster.png")
var anenemy=eninst.instance()
1 Like
:bust_in_silhouette: Reply From: timothybrentwood

You need to create a new Sprite node in your monster1 scene. Then in that Sprite node you need to set its texture to the texture located at res://monster.png.


func _startenemy():
    var enemyScene = load("res://monster1.tscn")
    var enemy_instance = enemyScene.instance()
    var enemy_sprite : Sprite = enemy_instance.get_node("Sprite")
    enemy_instance.position.x = -enemy_sprite.texture.get_size().x
    enemy_instance.position.y = (get_viewport_rect().size).y - enemy_sprite.texture.get_size().y

Note that “Sprite” inside of enemy_instance.get_node("Sprite") needs to be the exact name of the sprite you create in the monster1 scene.

Thank you! Now it is working!

Tomi | 2021-05-13 07:35

1 Like