I’m working on a 2D dungeon crawler/ rouge like game and I experience the following problem. When I resize the window new enemies spawn (not intended).
I’m doing the spawning logic at a room level, having 4 Marker2D and “randomly” spawning an enemy at the location of the Marker2D.
I attached the script below and here’s a clip of this happening:
On a closer view it looks like the whole game resets when the room needs to resize…
extends Node2D
@onready var room = $"."
@onready var spawn_point_1 = $SpawnPoint1
@onready var spawn_point_2 = $SpawnPoint2
@onready var spawn_point_3 = $SpawnPoint3
@onready var spawn_point_4 = $SpawnPoint4
const donut = preload("res://Enemy/Donut/donut.tscn")
var SpawnPoints = []
func _ready():
spawn_enemies()
func spawn_enemies():
SpawnPoints.append(spawn_point_1)
SpawnPoints.append(spawn_point_2)
SpawnPoints.append(spawn_point_3)
SpawnPoints.append(spawn_point_4)
for i in SpawnPoints:
if randi_range(1,5) > 2.5:
var new_donut = donut.instantiate()
room.add_child(new_donut)
new_donut.global_position = i.global_position
The Idea is to spawn the enemies when the room is initialized.
But as I observed later, also the position of the doors changes when I resize the window, which means that also the code that initializes the rooms get recalled (that one being also in the _ready() function).
So it looks to me that the _ready() functions gets called on window resize?
extends Node2D
var Room = preload("res://Rooms/room.tscn")
var player = preload("res://Player/player.tscn")
var loot_manager =preload("res://PowerUps/loot_manager.tscn")
var room_count = 5
var rooms = []
func _ready():
add_player()
randomize()
generate(room_count - 1)
func add_player():
await get_tree().create_timer(0.5).timeout
var main = get_tree().current_scene
player = player.instantiate()
main.add_child(player)
player.global_position = Vector2.ZERO
PlayerStats.health = PlayerStats.max_health
loot_manager = loot_manager.instantiate()
main.add_child(loot_manager)
loot_manager.global_position = Vector2.ZERO
func add_room(position):
if rooms.has(position):
return 0
rooms.append(position)
return 1
func generate(count):
randomize()
rooms = [Vector2i(0, 0)]
var from = rooms[-1]
while count > 0:
var dir = [Vector2i(-810,0), Vector2i(810,0), Vector2i(0,-490), Vector2i(0,490)].pick_random()
var to = from + dir
count -= add_room(to)
from = to
queue_redraw()
func _draw():
for r in rooms:
var Room = Room.instantiate()
var main = get_tree().current_scene
main.add_child(Room)
Room.global_position = r
func reload_level():
get_tree().reload_current_scene()
func _input(event):
if event.is_action_pressed("ui_accept"):
reload_level()