# Godot Engine Documentation ## Introduction The Godot Engine documentation is the official, comprehensive knowledge base for Godot Engine, a free and open-source community-driven 2D and 3D game engine. This documentation repository contains tutorials, API references, getting started guides, and detailed engine documentation to help developers create games across multiple platforms including desktop (Linux, macOS, Windows), mobile (Android, iOS), web, and consoles. The documentation is built using Sphinx and supports multiple languages through the Weblate translation platform, making Godot accessible to a global community of game developers. The documentation provides complete coverage of Godot's features, from basic scene management and node systems to advanced topics like shader programming, multiplayer networking, physics interpolation, and XR development. It includes step-by-step tutorials for creating first 2D and 3D games, comprehensive class references for all engine APIs, and best practices for game development. The repository is maintained by the Godot community and follows a structured organization with sections for getting started, tutorials, engine details, community resources, and a complete class reference that documents every function, signal, and property available in the engine. ## Core Node System ### Node Base Class The Node class is the fundamental building block of all Godot scenes, forming a tree structure where nodes can have parent-child relationships with unique naming requirements. ```gdscript extends Node func _ready(): # Called when node enters the scene tree print("Node is ready!") # Add child nodes programmatically var child = Node.new() child.name = "ChildNode" add_child(child) # Access children var my_child = get_node("ChildNode") print("Child count: ", get_child_count()) # Work with groups add_to_group("enemies") if is_in_group("enemies"): print("This node is an enemy") func _process(delta): # Called every frame, delta is time in seconds since last frame pass func _physics_process(delta): # Called at fixed intervals (60 times per second by default) pass ``` ### Scene Tree Management Create and manipulate the scene tree structure dynamically at runtime with node lifecycle management. ```gdscript extends Node func _ready(): # Find nodes in the tree var found = find_child("PlayerSprite", true, true) var all_enemies = find_children("Enemy*", "", true, true) # Duplicate nodes var clone = duplicate() # Queue node for deletion queue_free() # Remove and re-add nodes var child = get_child(0) remove_child(child) add_child(child) # Get parent and root var parent = get_parent() var root = get_tree().root # Set process modes set_process(true) set_physics_process(true) # Check if node can process if can_process(): print("Processing enabled") ``` ## Player Input and Movement ### Input Action Mapping Handle keyboard, mouse, and gamepad input through defined action maps with customizable key bindings. ```gdscript extends Area2D @export var speed = 400 # Pixels per second var screen_size func _ready(): screen_size = get_viewport_rect().size func _process(delta): var velocity = Vector2.ZERO # Check input actions (defined in Project Settings > Input Map) if Input.is_action_pressed("move_right"): velocity.x += 1 if Input.is_action_pressed("move_left"): velocity.x -= 1 if Input.is_action_pressed("move_down"): velocity.y += 1 if Input.is_action_pressed("move_up"): velocity.y -= 1 if velocity.length() > 0: velocity = velocity.normalized() * speed position += velocity * delta # Clamp to screen bounds position.x = clamp(position.x, 0, screen_size.x) position.y = clamp(position.y, 0, screen_size.y) ``` ### Character Controller with Animation Implement a complete character controller with movement, collision detection, and animation state management. ```gdscript extends CharacterBody2D @export var speed = 400.0 @export var jump_velocity = -400.0 var gravity = ProjectSettings.get_setting("physics/2d/default_gravity") func _physics_process(delta): # Apply gravity if not is_on_floor(): velocity.y += gravity * delta # Handle jump if Input.is_action_just_pressed("jump") and is_on_floor(): velocity.y = jump_velocity # Get input direction var direction = Input.get_axis("move_left", "move_right") # Apply movement if direction: velocity.x = direction * speed $AnimatedSprite2D.play("walk") $AnimatedSprite2D.flip_h = direction < 0 else: velocity.x = move_toward(velocity.x, 0, speed) $AnimatedSprite2D.play("idle") # Move with collision move_and_slide() ``` ## GDScript Basics ### Variables and Export Properties Declare variables with type hints and expose properties to the editor inspector for runtime customization. ```gdscript extends Node2D # Basic variable declaration var health = 100 var player_name: String = "Hero" # Export variables (appear in Inspector) @export var max_health: int = 100 @export var armor: float = 25.5 @export_range(0, 100) var mana: int = 50 @export var weapon: Texture2D @export_enum("Fire", "Ice", "Lightning") var element = "Fire" # Constants const MAX_SPEED = 500 const GRAVITY = 980 # Typed arrays var enemies: Array[Node] = [] var positions: Array[Vector2] = [] func _ready(): # Type inference var auto_typed := 42 # Inferred as int # Dictionary with type hints var inventory: Dictionary = { "sword": 1, "potion": 5, "gold": 100 } print("Health: ", health) print("Element: ", element) ``` ### Functions and Signals Define reusable functions with parameters and emit custom signals for event-driven communication between nodes. ```gdscript extends Node # Define custom signals signal health_changed(new_health, max_health) signal player_died signal item_collected(item_name, quantity) var health = 100 func _ready(): # Connect signal to function health_changed.connect(_on_health_changed) # Function with parameters and return value func take_damage(amount: int) -> bool: health -= amount health_changed.emit(health, 100) if health <= 0: player_died.emit() return true return false # Function with default parameters func heal(amount: int = 10) -> void: health = min(health + amount, 100) health_changed.emit(health, 100) # Callback function func _on_health_changed(new_health: int, max_health: int) -> void: print("Health: %d/%d" % [new_health, max_health]) # Static function static func calculate_distance(a: Vector2, b: Vector2) -> float: return a.distance_to(b) # Variadic function func log_message(level: String, args: Array) -> void: print("[%s] " % level, args) ``` ## C# Scripting ### C# Node Script Implement Godot functionality using C# with attributes for exported properties and signal definitions. ```csharp using Godot; public partial class Player : Area2D { // Export variables [Export] public int Speed { get; set; } = 400; [Export] public int MaxHealth { get; set; } = 100; [Export(PropertyHint.Range, "0,100,")] public int Mana { get; set; } = 50; // Define signals [Signal] public delegate void HealthChangedEventHandler(int newHealth, int maxHealth); [Signal] public delegate void PlayerDiedEventHandler(); public Vector2 ScreenSize; private int _health; public override void _Ready() { ScreenSize = GetViewportRect().Size; _health = MaxHealth; // Connect signals HealthChanged += OnHealthChanged; } public override void _Process(double delta) { var velocity = Vector2.Zero; if (Input.IsActionPressed("move_right")) velocity.X += 1; if (Input.IsActionPressed("move_left")) velocity.X -= 1; if (Input.IsActionPressed("move_down")) velocity.Y += 1; if (Input.IsActionPressed("move_up")) velocity.Y -= 1; if (velocity.Length() > 0) { velocity = velocity.Normalized() * Speed; Position += velocity * (float)delta; Position = new Vector2( x: Mathf.Clamp(Position.X, 0, ScreenSize.X), y: Mathf.Clamp(Position.Y, 0, ScreenSize.Y) ); } } public void TakeDamage(int amount) { _health -= amount; EmitSignal(SignalName.HealthChanged, _health, MaxHealth); if (_health <= 0) EmitSignal(SignalName.PlayerDied); } private void OnHealthChanged(int newHealth, int maxHealth) { GD.Print($"Health: {newHealth}/{maxHealth}"); } } ``` ### C# Collections and Variants Work with Godot collections, arrays, and the Variant type for dynamic typing in C#. ```csharp using Godot; using Godot.Collections; public partial class GameManager : Node { // Godot collections private Array _enemies = new Array(); private Dictionary _inventory = new Dictionary(); // Variant for dynamic typing private Variant _dynamicValue; public override void _Ready() { // Work with Arrays _enemies.Add(GetNode("Enemy1")); _enemies.Add(GetNode("Enemy2")); foreach (var enemy in _enemies) { enemy.Health = 100; } // Work with Dictionaries _inventory["sword"] = 1; _inventory["potion"] = 5; _inventory["gold"] = 100; if (_inventory.ContainsKey("sword")) { GD.Print("Sword count: ", _inventory["sword"]); } // Variant usage _dynamicValue = Variant.From(42); _dynamicValue = Variant.From("Hello"); _dynamicValue = Variant.From(new Vector2(10, 20)); // Check Variant type if (_dynamicValue.VariantType == Variant.Type.Vector2) { Vector2 vec = _dynamicValue.AsVector2(); GD.Print("Vector: ", vec); } } // Method with Variant parameters public void ProcessData(Variant data) { switch (data.VariantType) { case Variant.Type.Int: GD.Print("Integer: ", data.AsInt32()); break; case Variant.Type.String: GD.Print("String: ", data.AsString()); break; case Variant.Type.Object: GD.Print("Object: ", data.AsGodotObject()); break; } } } ``` ## 2D Graphics and Animation ### Animated Sprite Control 2D sprite animations with frame-based animation playback and state management. ```gdscript extends Node2D @onready var animated_sprite = $AnimatedSprite2D func _ready(): # Animation frames should be configured in the editor # SpriteFrames resource contains animations like "idle", "walk", "jump" # Play animation animated_sprite.play("idle") # Connect to animation finished signal animated_sprite.animation_finished.connect(_on_animation_finished) animated_sprite.frame_changed.connect(_on_frame_changed) func play_walk_animation(direction: int): animated_sprite.play("walk") animated_sprite.flip_h = direction < 0 animated_sprite.speed_scale = 1.5 # Play faster func play_attack(): animated_sprite.play("attack") # Wait for animation to finish await animated_sprite.animation_finished animated_sprite.play("idle") func _on_animation_finished(): print("Animation completed: ", animated_sprite.animation) if animated_sprite.animation == "death": queue_free() func _on_frame_changed(): print("Current frame: ", animated_sprite.frame) ``` ### Custom 2D Drawing Draw custom shapes, lines, and graphics using Canvas drawing commands with real-time updates. ```gdscript extends Node2D var circle_pos = Vector2(100, 100) var line_points = PackedVector2Array([Vector2(0, 0), Vector2(100, 50), Vector2(200, 0)]) func _ready(): # Request redraw each frame for animation set_process(true) func _process(delta): queue_redraw() # Request _draw() to be called func _draw(): # Draw filled circle draw_circle(circle_pos, 30, Color.RED) # Draw circle outline draw_arc(circle_pos, 50, 0, TAU, 32, Color.BLUE, 2.0) # Draw rectangle draw_rect(Rect2(200, 50, 100, 80), Color.GREEN) # Draw line draw_line(Vector2(0, 0), Vector2(100, 100), Color.WHITE, 2.0) # Draw polyline draw_polyline(line_points, Color.YELLOW, 3.0) # Draw polygon var polygon = PackedVector2Array([ Vector2(300, 100), Vector2(350, 150), Vector2(300, 200), Vector2(250, 150) ]) draw_colored_polygon(polygon, Color.PURPLE) # Draw text draw_string(ThemeDB.fallback_font, Vector2(10, 30), "Score: 100", HORIZONTAL_ALIGNMENT_LEFT, -1, 16, Color.WHITE) ``` ## 3D Scene Management ### 3D Node Transforms Manipulate 3D object positions, rotations, and scales in world and local space coordinates. ```gdscript extends Node3D @export var rotation_speed = 2.0 @export var move_speed = 5.0 func _ready(): # Set initial transform position = Vector3(0, 1, 0) rotation_degrees = Vector3(0, 45, 0) scale = Vector3(1, 1, 1) func _process(delta): # Rotate around Y axis rotate_y(rotation_speed * delta) # Move forward in local space translate(Vector3.FORWARD * move_speed * delta) # Look at a target var target = get_node("../Target") look_at(target.global_position, Vector3.UP) func set_transform_example(): # Global transform global_position = Vector3(10, 0, 10) global_rotation = Vector3(0, PI/2, 0) # Local transform relative to parent position = Vector3(5, 0, 0) # Get transform basis (rotation matrix) var forward = -transform.basis.z var right = transform.basis.x var up = transform.basis.y # Apply transform var new_transform = Transform3D() new_transform = new_transform.rotated(Vector3.UP, PI/4) new_transform.origin = Vector3(0, 2, 0) transform = new_transform ``` ### Camera and Viewport Configure 3D cameras with projection settings and viewport management for rendering control. ```gdscript extends Camera3D @export var target: Node3D @export var follow_speed = 5.0 @export var offset = Vector3(0, 5, 10) func _ready(): # Camera properties fov = 75 # Field of view in degrees near = 0.1 far = 1000 # Projection modes projection = PROJECTION_PERSPECTIVE # projection = PROJECTION_ORTHOGONAL # Make this the current camera make_current() func _process(delta): if target: # Smooth follow camera var target_pos = target.global_position + offset global_position = global_position.lerp(target_pos, follow_speed * delta) look_at(target.global_position, Vector3.UP) func screen_to_world(screen_pos: Vector2) -> Vector3: # Convert 2D screen position to 3D ray var ray_origin = project_ray_origin(screen_pos) var ray_dir = project_ray_normal(screen_pos) # Cast ray into scene var space_state = get_world_3d().direct_space_state var query = PhysicsRayQueryParameters3D.create(ray_origin, ray_origin + ray_dir * 1000) var result = space_state.intersect_ray(query) if result: return result.position return Vector3.ZERO ``` ## Physics and Collision ### 2D Physics Body Implement physics-based movement with collision detection and response for 2D characters. ```gdscript extends CharacterBody2D const SPEED = 300.0 const JUMP_VELOCITY = -400.0 const ACCELERATION = 1500.0 const FRICTION = 1200.0 var gravity = ProjectSettings.get_setting("physics/2d/default_gravity") func _physics_process(delta): # Apply gravity if not is_on_floor(): velocity.y += gravity * delta # Handle jump if Input.is_action_just_pressed("jump") and is_on_floor(): velocity.y = JUMP_VELOCITY # Get input direction var direction = Input.get_axis("move_left", "move_right") # Apply acceleration and friction if direction != 0: velocity.x = move_toward(velocity.x, direction * SPEED, ACCELERATION * delta) else: velocity.x = move_toward(velocity.x, 0, FRICTION * delta) # Move with collision handling move_and_slide() # Check collisions for i in get_slide_collision_count(): var collision = get_slide_collision(i) print("Collided with: ", collision.get_collider().name) print("Normal: ", collision.get_normal()) ``` ### Raycasting and Area Detection Perform spatial queries for line-of-sight detection and trigger-based interactions with overlap areas. ```gdscript extends Node2D @onready var raycast = $RayCast2D @onready var area = $Area2D func _ready(): # Configure raycast raycast.target_position = Vector2(100, 0) raycast.collision_mask = 1 # Only check layer 1 raycast.enabled = true # Connect area signals area.body_entered.connect(_on_body_entered) area.body_exited.connect(_on_body_exited) area.area_entered.connect(_on_area_entered) func _physics_process(delta): # Check raycast collision if raycast.is_colliding(): var collider = raycast.get_collider() var collision_point = raycast.get_collision_point() var collision_normal = raycast.get_collision_normal() print("Hit: ", collider.name, " at ", collision_point) func _on_body_entered(body: Node2D): print("Body entered area: ", body.name) if body.is_in_group("player"): print("Player entered!") func _on_body_exited(body: Node2D): print("Body exited area: ", body.name) func _on_area_entered(other_area: Area2D): print("Area overlap: ", other_area.name) # Manual spatial query func check_area(position: Vector2, radius: float): var space_state = get_world_2d().direct_space_state var query = PhysicsShapeQueryParameters2D.new() var shape = CircleShape2D.new() shape.radius = radius query.shape = shape query.transform = Transform2D(0, position) var result = space_state.intersect_shape(query) for item in result: print("Found: ", item.collider.name) ``` ## Resource Management ### Loading and Saving Resources Load assets and resources dynamically with proper error handling and resource management. ```gdscript extends Node func _ready(): # Load resources var texture = load("res://sprites/player.png") as Texture2D var scene = load("res://scenes/enemy.tscn") as PackedScene var audio = load("res://sounds/explosion.wav") as AudioStream # Preload at compile time (faster) var preloaded_scene = preload("res://scenes/bullet.tscn") # Check if resource exists if ResourceLoader.exists("res://data/level_1.json"): var data = load("res://data/level_1.json") # Instantiate scene var enemy_instance = scene.instantiate() add_child(enemy_instance) # Background loading load_resource_async("res://scenes/large_level.tscn") func load_resource_async(path: String): ResourceLoader.load_threaded_request(path) while true: var progress = [] var status = ResourceLoader.load_threaded_get_status(path, progress) if status == ResourceLoader.THREAD_LOAD_LOADED: var resource = ResourceLoader.load_threaded_get(path) print("Loaded: ", resource) break elif status == ResourceLoader.THREAD_LOAD_FAILED: print("Failed to load resource") break print("Loading progress: ", progress[0] * 100, "%") await get_tree().process_frame # Save and load custom resources func save_game_data(): var save_data = { "player_position": Vector2(100, 200), "score": 1500, "inventory": ["sword", "shield", "potion"] } var file = FileAccess.open("user://savegame.json", FileAccess.WRITE) file.store_string(JSON.stringify(save_data)) file.close() func load_game_data(): if FileAccess.file_exists("user://savegame.json"): var file = FileAccess.open("user://savegame.json", FileAccess.READ) var json_string = file.get_as_text() file.close() var json = JSON.new() var parse_result = json.parse(json_string) if parse_result == OK: var data = json.data print("Loaded data: ", data) return data return null ``` ## Signals and Events ### Custom Signal System Create event-driven architectures with custom signals for decoupled communication between game systems. ```gdscript # Global event bus (autoload singleton) extends Node signal player_health_changed(health, max_health) signal enemy_spawned(enemy) signal level_completed(score) signal game_over signal item_picked_up(item_type, quantity) # Player script extends CharacterBody2D signal died signal took_damage(amount) var health = 100 func _ready(): # Connect to global signals EventBus.game_over.connect(_on_game_over) # Connect own signals took_damage.connect(_on_took_damage) func take_damage(amount: int): health -= amount took_damage.emit(amount) EventBus.player_health_changed.emit(health, 100) if health <= 0: died.emit() EventBus.game_over.emit() func _on_took_damage(amount: int): print("Took ", amount, " damage!") func _on_game_over(): print("Game Over!") set_physics_process(false) # UI script extends Control func _ready(): # Connect to event bus EventBus.player_health_changed.connect(_on_health_changed) EventBus.item_picked_up.connect(_on_item_picked) func _on_health_changed(health: int, max_health: int): $HealthBar.value = float(health) / max_health * 100 func _on_item_picked(item_type: String, quantity: int): $ItemNotification.text = "Picked up %d %s" % [quantity, item_type] $ItemNotification.show() ``` ## Scene Management ### Scene Switching Transition between game scenes with loading screens and proper cleanup of resources. ```gdscript # SceneManager autoload singleton extends Node var current_scene = null func _ready(): var root = get_tree().root current_scene = root.get_child(root.get_child_count() - 1) func change_scene(path: String): # Deferred scene change call_deferred("_deferred_change_scene", path) func _deferred_change_scene(path: String): # Remove current scene current_scene.free() # Load and add new scene var new_scene = load(path).instantiate() get_tree().root.add_child(new_scene) get_tree().current_scene = new_scene current_scene = new_scene func change_scene_with_loading(path: String): # Show loading screen var loading_screen = preload("res://ui/loading_screen.tscn").instantiate() get_tree().root.add_child(loading_screen) # Start background loading ResourceLoader.load_threaded_request(path) while true: var progress = [] var status = ResourceLoader.load_threaded_get_status(path, progress) if status == ResourceLoader.THREAD_LOAD_LOADED: var scene = ResourceLoader.load_threaded_get(path) # Remove loading screen loading_screen.queue_free() # Change scene current_scene.queue_free() var new_scene = scene.instantiate() get_tree().root.add_child(new_scene) current_scene = new_scene break loading_screen.update_progress(progress[0]) await get_tree().process_frame # Usage in game extends Node func _ready(): # Simple scene change SceneManager.change_scene("res://scenes/main_menu.tscn") # Or reload current scene get_tree().reload_current_scene() # Or change scene with transition SceneManager.change_scene_with_loading("res://scenes/level_2.tscn") ``` ## Summary The Godot Engine documentation provides comprehensive guidance for game developers of all skill levels, from beginners creating their first 2D platformer to experienced developers implementing complex multiplayer systems or custom shaders. The documentation covers the complete Godot workflow including scene composition, scripting in both GDScript and C#, animation systems, physics simulation, audio management, user interface design, and platform-specific export configurations. Each tutorial includes practical code examples demonstrating real-world implementations of Godot's features with proper error handling and best practices. The documentation repository is designed to be browsable both online at docs.godotengine.org and offline as downloadable HTML or ePub archives, making it accessible regardless of internet connectivity. Integration patterns throughout the documentation emphasize Godot's node-based architecture, signal-driven event systems, and resource management, showing how to build scalable game architectures using autoload singletons, scene instancing, and proper separation of concerns. The class reference section provides exhaustive API documentation for every built-in class, method, property, and signal, while the tutorial sections demonstrate how these APIs work together to create complete game mechanics, making the documentation an essential resource for anyone developing games with Godot Engine.