0 votes

So i have 2 kinematic bodies under Ysort each containing different sprites (One player sprite and one enemy sprite.
Also the map is randomly generated world and also the player and enemy positions are mapped to world randomly.
So here's how the player spawn code looks like

onready var Player = get_node("YSort/Player")

func _ready() -> void:
    Player.position = map.player_spawn(arr[arr_length-1])

Here arr is the array of available Vector2 positions for spawning and arr_length is len(arr)
This works perfectly fine.

But for enemy spawns i decided to use preload the Kinamticbody2d node directly from the location of its .tscn file. Which looks like this

onready var enemy_grunt = preload("res://enemies/EnemyGrunt.tscn")

By doing this i was able to spawn the desired amount of EnemyGrunt kinamatiic bodies into a Node2D container called enemy_container. It looks like this

onready var enemy_container = get_node("YSort/enemy_container")
onready var enemy_grunt = preload("res://enemies/EnemyGrunt.tscn")

func spawn_enemy(num):
    for i in range(num):
        var enemy = enemy_grunt.instance()
        var random_key = get_random_key()
        var spawn_value = random_key
        enemy.position = map.enemy_spawn(spawn_value)

When i Place the enemy_container node and EnemyGrunt node under Ysort it wont work as the function is spawning enemy sprites directly from the preloaded EnemyGrunt.tscn.

And if i want Ysort to work i need to modify a code a little bit like this

onready var Enemy_Grunts = get_node("YSort/EnemyGrunt")
func spawn_enemy(num):
    for i in range(num):
        enemy_container.add_child(Enemy_Grunts )
        var random_key = get_random_key()
        var spawn_value = random_key
        Enemy_Grunts .position = map.enemy_spawn(spawn_value)

SO i hade to remove the line var enemy = enemy_grunt.instance() as it does not work with var EnemyGrunts = getnode("YSort/EnemyGrunt").

Without out instancing i'm not able to spawn the desired number of enemies using using num variable. If i want to add more i need to duplicate the EnemyGrunt node inside ysort. This is very counter productive.

So is there anyway i can add Ysort to sprites manually or make a instance of Enemy_Grunts under YSort ?

Scene Tab
The game looks without YSort

in Engine by (58 points)

1 Answer

0 votes
Best answer

Instead of adding enemy to the enemy container directly add child to YSort.
Change this to



by (58 points)
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.