#How to spawn scenes at random in the world.

21 messages · Page 1 of 1 (latest)

void hollow
#

Hi! I just finished the your first 2D game from Zero GDquest tutorial and learned a lot! I thought it would be kinda fun if when you moved throughout the world trees would spawn randomly around the player just out of view. Any idea on how to do this or where I should start? I have a little bit of code for it in the photo.

autumn oxide
#

The simplest answer is to use randf_range(min#,max#) for the x and y position of the trees when you spawn them.

The complicated answer is look into procedural generation. This creates a new map every time it's played.

#

Something like this could help.

https://www.youtube.com/watch?v=rlUzizExe2Q

Itch io Asset Pack : https://jackie-codes.itch.io/paradise...
Github : https://github.com/anonomity/Godot4Ti...

Support the Chanel
Patreon: / jackiecodes

Links
Itch: https://jackie-codes.itch.io/
Twitch: / jackie_codes
Twitter: / jackie_codes
Discord: / discord
website: jackie.codes

Equipment:
Drawing Pad: https://amzn.to/3VZ9...

▶ Play video
void hollow
#

Great! Thanks for the feedback! I think the procedural generation route is definitely more in line with what I was thinking but I might’ve bitten off more than I can chew with how much I know at the moment. Definitely something to work on though!

autumn oxide
exotic tusk
#

You can also just use the code used for the spawn_mob function. I have the same thing although I just call spawn_tree a few more times than spawn mobs. Then just to make sure I don't have a crazy amount of trees, I add a signal on the trees to queue_free() when they are out of view. This also gives you the side-effect of everytime you go to a new section it will have a different layout of trees!

void hollow
#

Oh that’s kinda smart, I don’t know why I didn’t think of that approach.

#

How would you implement queue free so it works when out of player sight?

#

@exotic tusk

exotic tusk
#

@void hollow add a child to the PineTree staticbody2d node of type VisibleOnScreenNotifier2D and then attach the _on_screen_exited() signal from the notifier to the tree's staticbody2d!

#

In the function you just queue_free

func _on_screen_exited():
    queue_free()
void hollow
#

So I’m giving this code a try and I’m very close but I think I’m deleting something I shouldn’t with the queue_free on accident because when using it my screen goes grayish🤔

exotic tusk
#

Sorry I didn't see these messages! Did you figure it out? When you run the game, look at it in remote and see if it has the visible on screen for each one or only the one. If we are spawning them there shouldn't be any in the scene before you start running the game, just like how the mobs aren't. So go to your PineTree scene and and the visible on screen notifier there, and attach that to the pine tree. You will have a small script on the tree, not the main game, that is queue free attached to the signal and nothing else!

obsidian hedge
# void hollow So I’m giving this code a try and I’m very close but I think I’m deleting someth...

Hey I just saw this - did you figure this out yet? I actually just did this the other day and can help if not. The "easy way" would be to simply copy how you have your enemies spawning, and create the tree. You can do it in less lines than this - which from what I know is better since it takes less time for the computer to read through each line (although it doesn't take long either way its always good to optimize where you can)
so here is what I had:
func spawn_tree():
var new_tree = preload("res://pine_tree.tscn").instantiate()
%PathFollow2D.progress_ratio = randf()
new_tree.global_position = %PathFollow2D.global_position
add_child(new_tree)
func _on_timer_timeout():
spawn_mob()
spawn_tree()

You can run this and it will spawn trees into the scene dynamically as you move throughout the world, and it does it in just a handfull of lines. (I cut out some other stuff I've added, such as bouncing off the trees when I dash, and didn't include the spawn_mob function since you've watched the video. This is the code I added though, and it works! Not sure if you wanted to do something different?
As for the comment above you can have them in the scene if you want them. I don't like my guy spawning into an empty world, so he starts with a few trees and an enemy on the screen. Then once I move around more stuff spawns around me as I move through the world

void hollow
#

Hey guys! Thank you for the input! @obsidian hedge @exotic tusk I haven’t worked on it in a bit but this is great! Yeah I definitely felt I was adding that child node to the wrong scene my brain just wasn’t figuring out it needed to go into the pine tree scene! Also thank you for the optimized lines! I’ll give it a go! I’ll let you know how it goes!

void hollow
#

Yes it worked 😁 @obsidian hedge @exotic tusk thank you so much for all of the help! Really thankful for the community here

void hollow
#

Actually one more small issue is that it seems to be deleting trees off screen now before my player gets there. So I have an initial tree area at the beginning which when I leave will queue free but the rest of the trees for some reason are not popping up because of the queue free code on the pine tree scene.

obsidian hedge
#

Just saw this let me go look at my code real quick because this doesn't happen to mine. Maybe I forgot a line hold on one minute

obsidian hedge
# void hollow Actually one more small issue is that it seems to be deleting trees off screen n...

Hey, do you have a piece of the script that is connected to the bullet by chance? The bullet is supposed to dispose of itself once it exits view, and I'm wondering if you've somehow tied those together?
Check to make sure those functions aren't interacting for some reason?
If they aren't here is my whole script for the game portion that deals with spawning enemies and the trees into the world.

obsidian hedge
# void hollow Actually one more small issue is that it seems to be deleting trees off screen n...

func spawn_tree():
var new_tree = preload("res://pine_tree.tscn").instantiate()
%PathFollow2D.progress_ratio = randf()
new_tree.global_position = %PathFollow2D.global_position
add_child(new_tree)
# lets try to bounceeeee
# Connect the collision signal to handle the bounce effect
var collision_shape = new_tree.get_node("CollisionShape2D") # Assuming CollisionShape2D is the node name
# collision_shape.connect("body_entered", self, "_on_tree_collision")

Handle the bounce effect when colliding with Pine Tree

func _on_tree_collision(body):
# Check if the colliding body is the player (or whatever object you want to bounce)
if body.is_in_group("player"):
# Add bouncing logic here
var bounce_direction = Vector2(-1, 1) # Adjust the direction as needed
var BOUNCE_STRENGTH = 500 # Adjust the strength of the bounce as needed
body.apply_impulse(body.global_position, bounce_direction * BOUNCE_STRENGTH)

func spawn_mob():
#score_label._on_score_label_squashed()
var new_mob = preload("res://mob.tscn").instantiate()
%PathFollow2D.progress_ratio = randf()
new_mob.global_position = %PathFollow2D.global_position
add_child(new_mob)
new_mob.squashed.connect(_on_mob_squashed)
#print("we spawning fr.")
#_help_me_please(new_mob)

func _on_timer_timeout():
spawn_mob()
spawn_tree()

func _on_player_health_depelted():
%GameOver.visible = true
get_tree().paused = true

#This is where the code is broken. Does not work
func _on_mob_squashed():
#print("Updating score")
score += 1
$Player/ScoreLabel.update_score(score)

#set the game over to visible
func _on_player_health_depleted():
%GameOver.visible = true
get_tree().paused = true