Instancing in front of the "player" and deleting things out of view

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

I’m trying to figure out how to make sure new instances(asteroids) spawn in front of my “player” when he is moving and the ones that are out of the view get deleted. because for now, each asteroid is spawning to slow behind the player. also how would you make them spin slowly when spawning, in different directions to look more like “realistic asteroids”, if the asteroids come from the bottom up it doesn’t bother me thats actually good to?
if this looks bad I barely know anything about codeing.

`extends Node2D
var pre_flyingobject= preload(“res://objects/flyingobject.tscn”)
var good_to_spawn=true

Called when the node enters the scene tree for the first time.

func _ready():
pass

func _process(delta):
pass

func _on_Area2D_body_entered(body):

if "flying" or "player" in body.name:
	good_to_spawn=false

func _on_Timer_timeout():
if good_to_spawn==true:
var new_flyingobject=pre_flyingobject.instance()
get_parent().add_child(new_flyingobject)
new_flyingobject.position=position
queue_free()`

:bust_in_silhouette: Reply From: Eric Ellingson

This is a partial answer.

In order to delete things that are out of view, you can just add a VisibilityNotifier2D node to your asteroid scene. Then you can listen for screen_exited signal, and then go ahead and remove the node.

Asteroid
    > VisibilityNotifier2D

# Asteroid.gd

# you can put whatever you want here for the range
const ROTATION_SPEED = [5, 90] # in degrees/second
const rotation_amount = 0
func _ready():
    $VisibilityNotifier2D.connect("screen_exited", self, "_on_screen_exited")
    set_random_rotation()

func _process(delta):
    rotation_degrees += delta * rotation_amount

func _on_screen_exited():
    queue_free()

func set_random_rotation():
    randomize()
    var direction = 1 if randf() > 0.5 else -1
    rotation_amount = direction * rand_range(ROTATION_SPEED[0], ROTATION_SPEED[1])

As far as where to instance nodes, can you provide a little more detail about the way things are set up?