乒乓球游戏:C++ GDExtension 实现

这个提交包含在:
2026-08-05 15:10:47 +08:00
父节点 7b7757c002
当前提交 7228d302f5
修改 117 个文件,包含 803 行新增121 行删除
-22
查看文件
@@ -1,22 +0,0 @@
#include "example.h"
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/core/defs.hpp>
#include <godot_cpp/godot.hpp>
using namespace godot;
void MyMath::_bind_methods() {
// 把 C++ 方法注册给 GDScript 调用
ClassDB::bind_method(D_METHOD("add", "a", "b"), &MyMath::add);
}
MyMath::MyMath() {
}
MyMath::~MyMath() {
}
int MyMath::add(int a, int b) {
return a + b;
}
-26
查看文件
@@ -1,26 +0,0 @@
#ifndef MARRY_EXAMPLE_H
#define MARRY_EXAMPLE_H
#include <godot_cpp/classes/ref_counted.hpp>
namespace godot {
// 示例 C++ 类:在 GDScript 里可以直接用 MyMath.new() 创建
// 之后把你的 C++ 逻辑类都加在这里
class MyMath : public RefCounted {
GDCLASS(MyMath, RefCounted)
protected:
static void _bind_methods();
public:
MyMath();
~MyMath();
// 示例方法:加法(GDScript 调用: m.add(3, 4) -> 7
int add(int a, int b);
};
}
#endif // MARRY_EXAMPLE_H
+136
查看文件
@@ -0,0 +1,136 @@
#include "pingpong_ball.h"
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/kinematic_collision2d.hpp>
#include <godot_cpp/classes/node2d.hpp>
#include <godot_cpp/classes/viewport.hpp>
#include <godot_cpp/classes/window.hpp>
#include <godot_cpp/classes/scene_tree.hpp>
using namespace godot;
void PingPongBall::_bind_methods() {
// 属性
ClassDB::bind_method(D_METHOD("get_speed"), &PingPongBall::get_speed);
ClassDB::bind_method(D_METHOD("set_speed", "value"), &PingPongBall::set_speed);
ClassDB::add_property("PingPongBall", PropertyInfo(Variant::FLOAT, "speed"), "set_speed", "get_speed");
// 方法
ClassDB::bind_method(D_METHOD("reset"), &PingPongBall::reset);
// 信号
ADD_SIGNAL(MethodInfo("scored", PropertyInfo(Variant::INT, "which")));
}
PingPongBall::PingPongBall() {
speed = 400.0f;
}
PingPongBall::~PingPongBall() {
}
void PingPongBall::_ready() {
reset();
}
void PingPongBall::_draw() {
// 画一个白色圆形表示球
draw_circle(Vector2(0.0f, 0.0f), 12.0f, Color(1.0f, 1.0f, 1.0f));
}
void PingPongBall::_physics_process(double delta) {
queue_redraw();
Vector2 velocity = direction * speed * (float)delta;
Ref<KinematicCollision2D> collision = move_and_collide(velocity);
if (collision.is_valid()) {
// 计算反弹方向
Vector2 normal = collision->get_normal();
direction = direction.bounce(normal);
// 根据碰撞法线判断碰撞对象类型
// 法线主要水平 → 碰到球拍(左右反弹)
// 法线主要垂直 → 碰到上下墙(上下反弹)
// 如果法线接近水平且球已经接近左右边界 → 得分
Object *collider = collision->get_collider();
if (collider) {
Node *collider_node = Object::cast_to<Node>(collider);
if (collider_node) {
StringName node_name = collider_node->get_name();
// 判断是不是球拍(球拍名字包含 "Paddle"
if (node_name.find("Paddle") != -1) {
// 碰到球拍,微调角度(根据击中位置)
Node2D *collider_2d = Object::cast_to<Node2D>(collider_node);
if (collider_2d) {
float hit_offset = (get_global_position().y - collider_2d->get_global_position().y) / 60.0f;
hit_offset = CLAMP(hit_offset, -1.0f, 1.0f);
direction.y += hit_offset * 0.5f;
direction = direction.normalized();
}
}
}
}
// 确保方向始终有效
direction = direction.normalized();
}
// 检测是否出界(得分判定)
Viewport *viewport = get_viewport();
if (viewport) {
Vector2 screen_size = viewport->get_visible_rect().size;
Vector2 pos = get_global_position();
if (pos.x < -50.0f) {
// 球从左边出界,右边得分
emit_signal("scored", 1);
reset();
} else if (pos.x > screen_size.x + 50.0f) {
// 球从右边出界,左边得分
emit_signal("scored", 0);
reset();
}
// Y 方向边界限制(防止飞出屏幕)
if (pos.y < 0.0f) {
set_global_position(Vector2(pos.x, 0.0f));
direction.y = std::abs(direction.y);
} else if (pos.y > screen_size.y) {
set_global_position(Vector2(pos.x, screen_size.y));
direction.y = -std::abs(direction.y);
}
}
}
void PingPongBall::reset() {
// 回到屏幕中央
Viewport *viewport = get_viewport();
if (viewport) {
Vector2 screen_size = viewport->get_visible_rect().size;
set_global_position(screen_size / 2.0f);
} else {
set_global_position(Vector2(640.0f, 360.0f));
}
// 随机方向(-45° 到 45° 之间,向左或向右随机)
float angle = (UtilityFunctions::randf() - 0.5f) * Math_PI / 2.0f; // -45° ~ 45°
int side = (UtilityFunctions::randf() > 0.5f) ? 1 : -1;
direction = Vector2((float)side * std::cos(angle), std::sin(angle)).normalized();
// 确保水平分量足够(避免球过于垂直)
if (std::abs(direction.x) < 0.3f) {
direction.x = (direction.x > 0 ? 1.0f : -1.0f) * 0.3f;
direction = direction.normalized();
}
}
void PingPongBall::set_speed(float p_speed) {
speed = p_speed;
}
float PingPongBall::get_speed() const {
return speed;
}
+38
查看文件
@@ -0,0 +1,38 @@
#ifndef PINGPONG_BALL_H
#define PINGPONG_BALL_H
#include <godot_cpp/classes/character_body2d.hpp>
namespace godot {
class PingPongBall : public CharacterBody2D {
GDCLASS(PingPongBall, CharacterBody2D)
private:
float speed = 300.0f;
Vector2 direction = Vector2(1.0f, 0.0f);
protected:
static void _bind_methods();
public:
PingPongBall();
~PingPongBall();
void _physics_process(double delta) override;
void _ready() override;
void _draw() override;
// 重置球到屏幕中央,以随机角度发射
void reset();
// 属性 getter/setter
void set_speed(float p_speed);
float get_speed() const;
// 信号: scored(int which) — 0=左边得分, 1=右边得分
};
}
#endif // PINGPONG_BALL_H
+114
查看文件
@@ -0,0 +1,114 @@
#include "pingpong_game.h"
#include "pingpong_ball.h"
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/scene_tree.hpp>
using namespace godot;
void PingPongGame::_bind_methods() {
// 属性
ClassDB::bind_method(D_METHOD("get_left_score"), &PingPongGame::get_left_score);
ClassDB::bind_method(D_METHOD("set_left_score", "value"), &PingPongGame::set_left_score);
ClassDB::add_property("PingPongGame", PropertyInfo(Variant::INT, "left_score"), "set_left_score", "get_left_score");
ClassDB::bind_method(D_METHOD("get_right_score"), &PingPongGame::get_right_score);
ClassDB::bind_method(D_METHOD("set_right_score", "value"), &PingPongGame::set_right_score);
ClassDB::add_property("PingPongGame", PropertyInfo(Variant::INT, "right_score"), "set_right_score", "get_right_score");
ClassDB::bind_method(D_METHOD("get_max_score"), &PingPongGame::get_max_score);
ClassDB::bind_method(D_METHOD("set_max_score", "value"), &PingPongGame::set_max_score);
ClassDB::add_property("PingPongGame", PropertyInfo(Variant::INT, "max_score"), "set_max_score", "get_max_score");
// 方法
ClassDB::bind_method(D_METHOD("reset_game"), &PingPongGame::reset_game);
ClassDB::bind_method(D_METHOD("_on_ball_scored", "which"), &PingPongGame::_on_ball_scored);
// 信号
ADD_SIGNAL(MethodInfo("game_over", PropertyInfo(Variant::INT, "winner")));
}
PingPongGame::PingPongGame() {
left_score = 0;
right_score = 0;
max_score = 5;
}
PingPongGame::~PingPongGame() {
}
void PingPongGame::_ready() {
// 查找比分 Label
left_score_label = Object::cast_to<Label>(get_node_or_null("UI/LeftScore"));
right_score_label = Object::cast_to<Label>(get_node_or_null("UI/RightScore"));
// 连接球的得分信号
PingPongBall *ball = Object::cast_to<PingPongBall>(get_node_or_null("Ball"));
if (ball) {
ball->connect("scored", Callable(this, "_on_ball_scored"));
}
update_score_display();
}
void PingPongGame::_on_ball_scored(int which) {
if (which == 0) {
// 左边得分
right_score++;
} else {
// 右边得分
left_score++;
}
update_score_display();
// 检查是否有人获胜
if (left_score >= max_score) {
emit_signal("game_over", 0);
} else if (right_score >= max_score) {
emit_signal("game_over", 1);
}
}
void PingPongGame::reset_game() {
left_score = 0;
right_score = 0;
update_score_display();
}
void PingPongGame::update_score_display() {
if (left_score_label) {
left_score_label->set_text(String::num_int64(left_score));
}
if (right_score_label) {
right_score_label->set_text(String::num_int64(right_score));
}
}
void PingPongGame::set_left_score(int p_score) {
left_score = p_score;
update_score_display();
}
int PingPongGame::get_left_score() const {
return left_score;
}
void PingPongGame::set_right_score(int p_score) {
right_score = p_score;
update_score_display();
}
int PingPongGame::get_right_score() const {
return right_score;
}
void PingPongGame::set_max_score(int p_score) {
max_score = p_score;
}
int PingPongGame::get_max_score() const {
return max_score;
}
+52
查看文件
@@ -0,0 +1,52 @@
#ifndef PINGPONG_GAME_H
#define PINGPONG_GAME_H
#include <godot_cpp/classes/node2d.hpp>
#include <godot_cpp/classes/label.hpp>
namespace godot {
class PingPongGame : public Node2D {
GDCLASS(PingPongGame, Node2D)
private:
int left_score = 0;
int right_score = 0;
int max_score = 5;
Label *left_score_label = nullptr;
Label *right_score_label = nullptr;
void update_score_display();
protected:
static void _bind_methods();
public:
PingPongGame();
~PingPongGame();
void _ready() override;
// 得分处理
void _on_ball_scored(int which);
// 重置整局游戏
void reset_game();
// 属性 getter/setter
void set_left_score(int p_score);
int get_left_score() const;
void set_right_score(int p_score);
int get_right_score() const;
void set_max_score(int p_score);
int get_max_score() const;
// 信号: game_over(int winner) — 0=左边赢, 1=右边赢
};
}
#endif // PINGPONG_GAME_H
+110
查看文件
@@ -0,0 +1,110 @@
#include "pingpong_paddle.h"
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/classes/input.hpp>
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/node.hpp>
#include <godot_cpp/classes/scene_tree.hpp>
#include <godot_cpp/classes/viewport.hpp>
using namespace godot;
void PingPongPaddle::_bind_methods() {
// 属性
ClassDB::bind_method(D_METHOD("get_speed"), &PingPongPaddle::get_speed);
ClassDB::bind_method(D_METHOD("set_speed", "value"), &PingPongPaddle::set_speed);
ClassDB::add_property("PingPongPaddle", PropertyInfo(Variant::FLOAT, "speed"), "set_speed", "get_speed");
ClassDB::bind_method(D_METHOD("get_is_player"), &PingPongPaddle::get_is_player);
ClassDB::bind_method(D_METHOD("set_is_player", "value"), &PingPongPaddle::set_is_player);
ClassDB::add_property("PingPongPaddle", PropertyInfo(Variant::BOOL, "is_player"), "set_is_player", "get_is_player");
ClassDB::bind_method(D_METHOD("get_ball_path"), &PingPongPaddle::get_ball_path);
ClassDB::bind_method(D_METHOD("set_ball_path", "value"), &PingPongPaddle::set_ball_path);
ClassDB::add_property("PingPongPaddle", PropertyInfo(Variant::NODE_PATH, "ball_path"), "set_ball_path", "get_ball_path");
}
PingPongPaddle::PingPongPaddle() {
speed = 350.0f;
is_player = true;
}
PingPongPaddle::~PingPongPaddle() {
}
void PingPongPaddle::_draw() {
// 画一个白色矩形表示球拍
draw_rect(Rect2(Vector2(-10.0f, -60.0f), Vector2(20.0f, 120.0f)), Color(1.0f, 1.0f, 1.0f));
}
void PingPongPaddle::_physics_process(double delta) {
queue_redraw();
float move_amount = 0.0f;
if (is_player) {
// 玩家控制:读取上下输入
Input *input = Input::get_singleton();
if (input->is_action_pressed("ui_up")) {
move_amount = -1.0f;
} else if (input->is_action_pressed("ui_down")) {
move_amount = 1.0f;
}
} else {
// AI 控制:追踪球的位置
if (!ball_path.is_empty()) {
Node *node = get_node_or_null(ball_path);
if (node) {
Node2D *ball = Object::cast_to<Node2D>(node);
if (ball) {
float ball_y = ball->get_global_position().y;
float paddle_y = get_global_position().y;
if (ball_y < paddle_y - 20.0f) {
move_amount = -1.0f;
} else if (ball_y > paddle_y + 20.0f) {
move_amount = 1.0f;
}
}
}
}
}
// 移动
Vector2 velocity = Vector2(0.0f, move_amount * speed * (float)delta);
move_and_collide(velocity);
// 限制移动范围(不超出屏幕)
Viewport *viewport = get_viewport();
if (viewport) {
Vector2 screen_size = viewport->get_visible_rect().size;
Vector2 pos = get_global_position();
if (pos.y < half_height) {
set_global_position(Vector2(pos.x, half_height));
} else if (pos.y > screen_size.y - half_height) {
set_global_position(Vector2(pos.x, screen_size.y - half_height));
}
}
}
void PingPongPaddle::set_speed(float p_speed) {
speed = p_speed;
}
float PingPongPaddle::get_speed() const {
return speed;
}
void PingPongPaddle::set_is_player(bool p_is_player) {
is_player = p_is_player;
}
bool PingPongPaddle::get_is_player() const {
return is_player;
}
void PingPongPaddle::set_ball_path(const NodePath &p_path) {
ball_path = p_path;
}
NodePath PingPongPaddle::get_ball_path() const {
return ball_path;
}
+40
查看文件
@@ -0,0 +1,40 @@
#ifndef PINGPONG_PADDLE_H
#define PINGPONG_PADDLE_H
#include <godot_cpp/classes/character_body2d.hpp>
namespace godot {
class PingPongPaddle : public CharacterBody2D {
GDCLASS(PingPongPaddle, CharacterBody2D)
private:
float speed = 350.0f;
bool is_player = true;
NodePath ball_path;
float half_height = 60.0f; // 球拍半高,用于限制移动范围
protected:
static void _bind_methods();
public:
PingPongPaddle();
~PingPongPaddle();
void _physics_process(double delta) override;
void _draw() override;
// 属性 getter/setter
void set_speed(float p_speed);
float get_speed() const;
void set_is_player(bool p_is_player);
bool get_is_player() const;
void set_ball_path(const NodePath &p_path);
NodePath get_ball_path() const;
};
}
#endif // PINGPONG_PADDLE_H
+17 -10
查看文件
@@ -1,6 +1,8 @@
#include "register_types.h"
#include "example.h"
#include "pingpong_ball.h"
#include "pingpong_paddle.h"
#include "pingpong_game.h"
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/core/defs.hpp>
@@ -8,29 +10,34 @@
using namespace godot;
void initialize_marry_module(ModuleInitializationLevel p_level) {
void initialize_pingpang_module(ModuleInitializationLevel p_level) {
if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
return;
}
// 在这里注册所有 C++
GDREGISTER_CLASS(MyMath);
// 注册所有游戏
GDREGISTER_CLASS(PingPongBall);
GDREGISTER_CLASS(PingPongPaddle);
GDREGISTER_CLASS(PingPongGame);
}
void uninitialize_marry_module(ModuleInitializationLevel p_level) {
void uninitialize_pingpang_module(ModuleInitializationLevel p_level) {
if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
return;
}
// godot-cpp 在库卸载时自动清理类,无需手动注销
// godot-cpp 在库卸载时自动清理类
}
// Godot 加载扩展的入口(dll 导出符号)
extern "C" {
// Initialization.
GDExtensionBool GDE_EXPORT marry_library_init(GDExtensionInterfaceGetProcAddress p_get_proc_address, GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization) {
GDExtensionBool GDE_EXPORT pingpang_library_init(
GDExtensionInterfaceGetProcAddress p_get_proc_address,
GDExtensionClassLibraryPtr p_library,
GDExtensionInitialization *r_initialization
) {
godot::GDExtensionBinding::InitObject init_obj(p_get_proc_address, p_library, r_initialization);
init_obj.register_initializer(initialize_marry_module);
init_obj.register_terminator(uninitialize_marry_module);
init_obj.register_initializer(initialize_pingpang_module);
init_obj.register_terminator(uninitialize_pingpang_module);
init_obj.set_minimum_library_initialization_level(MODULE_INITIALIZATION_LEVEL_SCENE);
return init_obj.init();
+5 -5
查看文件
@@ -1,11 +1,11 @@
#ifndef MARRY_REGISTER_TYPES_H
#define MARRY_REGISTER_TYPES_H
#ifndef PINGPANG_REGISTER_TYPES_H
#define PINGPANG_REGISTER_TYPES_H
#include <godot_cpp/core/class_db.hpp>
using namespace godot;
void initialize_marry_module(ModuleInitializationLevel p_level);
void uninitialize_marry_module(ModuleInitializationLevel p_level);
void initialize_pingpang_module(ModuleInitializationLevel p_level);
void uninitialize_pingpang_module(ModuleInitializationLevel p_level);
#endif // MARRY_REGISTER_TYPES_H
#endif // PINGPANG_REGISTER_TYPES_H