0 votes

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 (getviewportrect().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()
get_parent().add_child(anenemy)
anenemy.position.x=-itssprite.texture.get_size.x
anenemy.position.y=(get_viewport_rect().size).y-itssprite.texture.get_size.y
Godot version 3.3 Stable Official Win64
in Engine by (47 points)

1 Answer

0 votes
Best answer

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.

Then:

func _startenemy():
    var enemyScene = load("res://monster1.tscn")
    var enemy_instance = enemyScene.instance()
    get_parent().add_child(enemy_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.

by (3,425 points)
selected by

Thank you! Now it is working!

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 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 webmaster@godotengine.org with your username.