Guide to the Godot game engine/Manipulate scene tree

So, you can add, rename, move and delete nodes in the editor. But how do you do it with code? This is such an important thing, yet it isn't obvious how to do it.

Basic manipulation

edit

This is how to create a bullet, add it to the scene, and delete it after 10 seconds:

player.gd
extends KinematicBody2D

func _physics_process(delta):
  if Input.is_action_just_pressed("shoot"):
    # Create bullet and add it as a child of its parent:
    var bullet=preload("res://bullet.tscn").instance()
    get_parent().add_child(bullet)


bullet.gd
extends Area2D

var timer:=0.0
var dir = 1 # Right = 1, Left = -1

func _physics_process(delta):
  # Increase the timer
  timer+=delta
  if timer >= 10:
    # Ten seconds have passed - delete on next frame
    queue_free()
  position.x+=(5 * dir) *delta

queue_free(): Deletes a node on the next frame, or after the node's script has finished.

add_child(node: Node): Adds node as a child of the node that the add_child() was called on, providing node doesn't already have a parent.

Advanced control

edit

How do you close your game? How do you pause/unpause your game (the correct way)?

# Remember: call "get_tree()" before calling any of these

# Quit the game/app
get_tree().quit()

# Pause
get_tree().paused=true # Or "false" to unpause
# Pausing stops "_physics_process()".
# It also stops "_process()" and "*_input()" if pause mode is not "pause_mode_process" for the node.