强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

Godot 4 GDScript 教程 / Godot 4 简介与新特性

Godot 4 简介与新特性

Godot 4 是开源游戏引擎 Godot 的最新主要版本,于 2023 年正式发布,带来了革命性的渲染系统、全新的 GDScript 2.0 语言特性以及大量工作流改进。

1. Godot 4 发布历程

版本发布时间里程碑事件
Godot 3.02018 年 1 月GLES2/GLES3 渲染器、C# 支持
Godot 3.52022 年 8 月最后的 3.x 版本
Godot 4.02023 年 3 月Vulkan 渲染、GDScript 2.0、GDExtension
Godot 4.12023 年 7 月性能优化、编辑器改进
Godot 4.22023 年 11 月GPU 粒子改进、新导航系统
Godot 4.32024 年 8 月渲染优化、移动端改进
Godot 4.42025 年 3 月新物理引擎、AI 导航

2. 核心新特性一览

2.1 Vulkan 渲染器

Godot 4 用 Vulkan 后端取代了旧的 OpenGL ES,带来了显著的渲染性能提升:

# 在项目设置中可以配置渲染后端
# 渲染 > 渲染器 > 渲染方法
# 可选: forward_plus, mobile, gl_compatibility

# 代码中获取渲染信息
func _ready():
    var rendering_info = RenderingServer.get_video_adapter_name()
    var api_version = RenderingServer.get_video_adapter_api_version()
    print("GPU: %s" % rendering_info)
    print("API: %s" % api_version)

Vulkan vs GLES3 对比:

特性VulkanGLES3 (兼容模式)
渲染性能⭐⭐⭐⭐⭐⭐⭐⭐
高级特效全部支持部分支持
移动端兼容Android/iOS所有平台
全局光照SDFGI/VoxelGI仅烘焙光照
GPU 粒子完全支持CPU 粒子
最低系统Windows 10+, 较新显卡广泛兼容

⚠️ 注意: 如果目标平台是低端移动设备或 Web,建议使用 gl_compatibility 渲染方法。

2.2 GDScript 2.0

GDScript 2.0 引入了类型系统、注解和更现代的语法:

# GDScript 2.0 示例 - 类型化变量和函数
extends CharacterBody2D

# 类型化变量声明
var health: int = 100
var speed: float = 300.0
var player_name: String = "Hero"

# @export 让变量在编辑器中可见
@export var max_health: int = 100
@export var move_speed: float = 200.0

# @onready 延迟到节点就绪后初始化
@onready var sprite: Sprite2D = $Sprite2D
@onready var animation_player: AnimationPlayer = $AnimationPlayer

# 类型化函数
func take_damage(amount: int) -> void:
    health = clampi(health - amount, 0, max_health)
    if health <= 0:
        die()

func die() -> void:
    animation_player.play("death")
    await animation_player.animation_finished
    queue_free()

# Lambda 表达式
func setup_callbacks():
    var on_hit = func(damage: int): take_damage(damage)
    signal_hit.connect(on_hit)

2.3 物理系统重写

Godot 4 重写了物理引擎,将 KinematicBody 替换为更强大的 CharacterBody3D/CharacterBody2D

# Godot 4 CharacterBody2D 示例
extends CharacterBody2D

@export var speed: float = 300.0
@export var jump_velocity: float = -400.0

# 获取重力设置
var gravity: float = ProjectSettings.get_setting("physics/2d/default_gravity")

func _physics_process(delta: float) -> void:
    # 应用重力
    if not is_on_floor():
        velocity.y += gravity * delta

    # 跳跃
    if Input.is_action_just_pressed("jump") and is_on_floor():
        velocity.y = jump_velocity

    # 水平移动
    var direction = Input.get_axis("move_left", "move_right")
    velocity.x = direction * speed

    # Godot 4 的 move_and_slide() 不需要参数
    move_and_slide()

⚠️ 注意: Godot 4 的 move_and_slide() 不再接收 velocity 参数,直接使用节点的 velocity 属性。

2.4 NavigationServer 导航系统

新的导航系统使用服务器架构,性能大幅提升:

# 2D 导航示例
extends CharacterBody2D

@onready var navigation_agent: NavigationAgent2D = $NavigationAgent2D

var target_position: Vector2

func move_to(target: Vector2) -> void:
    target_position = target
    navigation_agent.target_position = target

func _physics_process(delta: float) -> void:
    if navigation_agent.is_navigation_finished():
        return

    var next_path_position = navigation_agent.get_next_path_position()
    var direction = global_position.direction_to(next_path_position)
    velocity = direction * 300.0
    move_and_slide()

💡 提示: NavigationServer 支持动态障碍物和导航网格实时更新,非常适合 RTS 游戏。

2.5 GDExtension

GDExtension 允许使用 C/C++ 扩展引擎功能,无需重新编译引擎:

// GDExtension C++ 示例(简化版)
#include <godot_cpp/classes/sprite2d.hpp>
#include <godot_cpp/core/class_db.hpp>

using namespace godot;

class MySprite : public Sprite2D {
    GDCLASS(MySprite, Sprite2D)

protected:
    static void _bind_methods() {
        ClassDB::bind_method(D_METHOD("custom_function"), &MySprite::custom_function);
    }

public:
    void custom_function() {
        // 自定义高性能函数
    }
};

// 注册扩展
void initialize_extension(ModuleInitializationLevel p_level) {
    if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) return;
    ClassDB::register_class<MySprite>();
}

3. Godot 3 vs Godot 4 对比表

功能领域Godot 3Godot 4迁移难度
渲染后端GLES2/GLES3Vulkan/GLES3🔴 高
脚本语言GDScript 1.0GDScript 2.0🟡 中
信号系统connect("signal", target, "method")signal.connect(callable)🟡 中
物理节点KinematicBodyCharacterBody🟡 中
粒子系统CPUParticles/GPUParticlesGPUParticles (全部GPU)🟡 中
导航Navigation2D/3D 节点NavigationServer🟡 中
动画AnimationPlayerAnimationPlayer + AnimationMixer🟢 低
UI 系统ControlControl (基本不变)🟢 低
扩展GDNativeGDExtension🔴 高
场景格式.tscn (Godot 3).tscn (Godot 4, 不兼容)🔴 高
资源格式.tres.tres (不兼容)🔴 高

4. 与 Unity/Unreal 对比

特性Godot 4UnityUnreal Engine
授权协议MIT (完全免费)商业授权商业授权
引擎大小~100MB~5GB~50GB
脚本语言GDScript/C#C#/Visual ScriptC++/Blueprint
学习曲线⭐⭐ 简单⭐⭐⭐ 中等⭐⭐⭐⭐ 困难
2D 支持⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
3D 支持⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
移动端⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
社区规模中型大型大型
适合项目独立游戏/2D/中小型3D各类商业游戏AAA/大型3D

💡 提示: Godot 完全免费且开源,无收入分成,非常适合独立开发者和教育用途。

5. 下载与安装

5.1 下载方式

平台下载方式推荐度
Windows官网下载 zip⭐⭐⭐⭐⭐
macOS官网下载 dmg⭐⭐⭐⭐⭐
Linux官网下载 AppImage⭐⭐⭐⭐⭐
SteamSteam 商店搜索 Godot⭐⭐⭐⭐
包管理器Flatpak/Snap (可能非最新)⭐⭐⭐

5.2 安装步骤

# Linux (AppImage)
chmod +x Godot_v4.4-stable_linux.x86_64.AppImage
./Godot_v4.4-stable_linux.x86_64.AppImage

# macOS (Homebrew)
brew install --cask godot

# Windows (Scoop)
scoop install godot

# Flatpak (Linux)
flatpak install flathub org.godotengine.Godot

⚠️ 注意: 从官网下载的是标准版,如需 .NET/C# 支持,需要下载 .NET 版本。

6. 创建第一个项目

6.1 项目管理器

启动 Godot 后会看到项目管理器:

  1. 点击 新建项目
  2. 输入项目名称(如 “MyFirstGame”)
  3. 选择项目路径
  4. 选择渲染器(推荐 Forward+
  5. 点击 创建并编辑

6.2 创建第一个场景

# main.gd - 主场景脚本
extends Node2D

# 使用 @onready 获取子节点引用
@onready var label: Label = $UI/Label
@onready var player: Sprite2D = $Player

# 游戏变量
var score: int = 0
var game_time: float = 0.0

func _ready() -> void:
    """场景就绪时调用"""
    print("游戏开始!")
    update_score_display()

func _process(delta: float) -> void:
    """每帧调用"""
    game_time += delta
    
    # 简单的玩家移动
    var velocity = Vector2.ZERO
    if Input.is_action_pressed("ui_right"):
        velocity.x += 1
    if Input.is_action_pressed("ui_left"):
        velocity.x -= 1
    if Input.is_action_pressed("ui_down"):
        velocity.y += 1
    if Input.is_action_pressed("ui_up"):
        velocity.y -= 1
    
    player.position += velocity.normalized() * 200 * delta

func add_score(points: int) -> void:
    """增加分数"""
    score += points
    update_score_display()

func update_score_display() -> void:
    """更新分数显示"""
    label.text = "分数: %d" % score

6.3 运行场景

F5 或点击右上角的 运行项目 按钮。首次运行会提示设置主场景。

7. 游戏开发场景示例

场景1:2D 平台跳跃游戏

# platformer_player.gd
extends CharacterBody2D

@export var speed: float = 300.0
@export var jump_force: float = -500.0
@export var gravity_scale: float = 1.0

@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D

var gravity: float = ProjectSettings.get_setting("physics/2d/default_gravity")

func _physics_process(delta: float) -> void:
    # 重力
    if not is_on_floor():
        velocity.y += gravity * gravity_scale * delta
    
    # 跳跃
    if Input.is_action_just_pressed("jump") and is_on_floor():
        velocity.y = jump_force
        animated_sprite.play("jump")
    
    # 水平移动
    var direction = Input.get_axis("move_left", "move_right")
    velocity.x = direction * speed
    
    # 动画切换
    if is_on_floor():
        if direction != 0:
            animated_sprite.play("run")
            animated_sprite.flip_h = direction < 0
        else:
            animated_sprite.play("idle")
    
    move_and_slide()

场景2:RPG 对话系统

# dialogue_manager.gd
extends Node

signal dialogue_started(npc_name: String)
signal dialogue_ended
signal dialogue_line(speaker: String, text: String)

var is_active: bool = false
var current_dialogue: Array[Dictionary] = []
var current_index: int = 0

func start_dialogue(npc_name: String, lines: Array[Dictionary]) -> void:
    if is_active:
        return
    
    is_active = true
    current_dialogue = lines
    current_index = 0
    dialogue_started.emit(npc_name)
    show_next_line()

func show_next_line() -> void:
    if current_index >= current_dialogue.size():
        end_dialogue()
        return
    
    var line = current_dialogue[current_index]
    dialogue_line.emit(line["speaker"], line["text"])
    current_index += 1

func end_dialogue() -> void:
    is_active = false
    current_dialogue = []
    current_index = 0
    dialogue_ended.emit()

func _input(event: InputEvent) -> void:
    if is_active and event.is_action_pressed("interact"):
        show_next_line()

8. 社区生态

8.1 官方资源

资源网址说明
官方文档docs.godotengine.org完整 API 文档
Q&A 问答ask.godotengine.org官方问答社区
GitHubgithub.com/godotengine源代码仓库
Asset Librarygodotengine.org/asset-library资源商店

8.2 社区资源

资源说明
GDQuest高质量 Godot 教程
KidsCanCode英文视频教程
Godot 社区Discord/Reddit 社区
GDScript 代码片段社区分享的代码

8.3 推荐学习路径

初学者路径:
1. 完成官方 "Your First 2D Game" 教程
2. 学习 GDScript 2.0 基础语法
3. 理解节点和场景树
4. 尝试制作简单的 2D 游戏

进阶路径:
1. 深入物理系统和碰撞
2. 学习 UI 系统
3. 掌握动画系统
4. 学习 Shader 编程

高级路径:
1. GDExtension C++ 扩展
2. 插件开发
3. 多人网络
4. 性能优化

9. 扩展阅读


下一章: 02 - 安装与项目设置