I tried using this Node to spawn enemies and keep gettin this error:
“Invalid get index ‘global_position’ (on base: ‘Array[Node]’).”
What am I doing wrong? I was following a tutorial on youtube.
script attached to node:
extends Node2D
#Broken! Cant find player.global_position for some reason. Dont add to Gamemode2 Scene!
u/export var spawns: Array[SpawnInfo] = []
u/onready var gamer = get_tree().get_nodes_in_group("player")
var time = 0
func _on_timer_timeout():
print(gamer.global_position)
time += 1
var enemy_spawns = spawns
for i in enemy_spawns:
if time >= i.time_start and time <= i.time_end:
if i.spawn_delay_counter < i.enemy_spawn_delay:
i.spawn_delay_counter += 1
else:
i.spawn_delay_counter = 0
var new_enemy = load(str(i.enemy.resource_path))
var counter = 0
while counter < i.enemyNum:
var enemy_spawn = new_enemy.instantiate()
enemy_spawn.position = get_random_position()
add_child(enemy_spawn)
counter += 1
#emit_signal("changetime",time)
func get_random_position():
var vpr = get_viewport_rect().size * randf_range(1.1,1.4)
var top_left = Vector2(gamer.global_position.x - vpr.x/2, gamer.global_position.y - vpr.y/2)
var top_right = Vector2(gamer.global_position.x + vpr.x/2, gamer.global_position.y - vpr.y/2)
var bottom_left = Vector2(gamer.global_position.x - vpr.x/2, gamer.global_position.y + vpr.y/2)
var bottom_right = Vector2(gamer.global_position.x + vpr.x/2,gamer.global_position.y + vpr.y/2)
var pos_side = ["up","down","right","left"].pick_random() #picks random value from target array
var spawn_pos1 = Vector2.ZERO #initiating
var spawn_pos2 = Vector2.ZERO
match pos_side: #switch statement
"up":
spawn_pos1 = top_left
spawn_pos2 = top_right
"down":
spawn_pos1 = bottom_left
spawn_pos2 = bottom_right
"right":
spawn_pos1 = top_right
spawn_pos2 = bottom_right
"left":
spawn_pos1 = top_left
spawn_pos2 = bottom_left
var x_spawn = randf_range(spawn_pos1.x, spawn_pos2.x)
var y_spawn = randf_range(spawn_pos1.y,spawn_pos2.y)
return Vector2(x_spawn,y_spawn)
Spawninfo Resource
extends Resource
class_name SpawnInfo
u/export var time_start: int
u/export var time_end: int
u/export var enemy: Resource
u/export var enemyNum: int
u/export var enemy_spawn_delay: int
var spawn_delay_counter = 0