Godot 官方2D C#重构(1):雪花碰撞

前言

Godot 官方 教程
Godot 2d 官方案例C#重构 专栏
Godot 2d 重构 github地址

实现效果

难点介绍

Godot GDScript和C# 对应关系大部分靠猜

文件导入

  • 资源地址:默认为res://开头
  • 2D贴图导入类型:Texture2D
csharp 复制代码
public Texture2D Bullet_Image = new Texture2D();
Bullet_Image = GD.Load<Texture2D>("res://bullet.png");

2D属性赋值,PhysicsServer

PhysicsServer 用于给赋值属性和属性初始化

csharp 复制代码
Shape = PhysicsServer2D.CircleShapeCreate();
PhysicsServer2D.ShapeSetData(Shape,8);

刷新UI

在_Process里面调用QueueRedraw

csharp 复制代码
public override void _Process(double delta)
{
	QueueRedraw();
}

绘制UI

生成2D贴图

csharp 复制代码
DrawTexture(Texture2D img, Vector2 position);

重载_Draw函数

csharp 复制代码
    public override void _Draw()
    {
		var offset = -Bullet_Image.GetSize();
		//Godot重载了对应的运算符
		offset = offset /2;
		
        foreach (var item in bullets)
		{
			DrawTexture(Bullet_Image, item.position + offset);
		}
        base._Draw();
    }

离开页面销毁

销毁

csharp 复制代码
PhysicsServer2D.FreeRid(item.body);

离开页面销毁

csharp 复制代码
    public override void _ExitTree()
    {
		foreach (var item in bullets)
		{
			PhysicsServer2D.FreeRid(item.body);
		}
		PhysicsServer2D.FreeRid(Shape);
        base._ExitTree();
    }

定位到鼠标位置

重载 _Input函数,获取鼠标参数

csharp 复制代码
public override void _Input(InputEvent @event)
{
	if(@event is InputEventMouseMotion)
	{
		var mouseEvent = (@event as InputEventMouseMotion);
		Position = mouseEvent.Position;
	}
    base._Input(@event);
}
相关推荐
anlog8 小时前
ini文件读取,EXE同目录文件读取
c#·ini
rockey6278 小时前
AScript之编译递归函数
c#·.net·script·动态脚本
ggb喔9 小时前
AI 原生攻防时代:2026 年渗透测试与逆向开发的范式重构
人工智能·重构
微三云 - 廖会灵 (私域系统开发)14 小时前
重资产的突围:当酒店遇上 RWA,用服务权益数字化重构产业供需关系
人工智能·重构
yue00814 小时前
winform控件篇-按钮
c#
DevOpenClub19 小时前
Markdown、HTML 和 PPT 如何稳定交付:文档转换任务的幂等发布流程
开发语言·前端·c#·html·powerpoint
软件黑马王子19 小时前
3.单例模式问题1:构造函数
开发语言·单例模式·c#
软件黑马王子20 小时前
4.单例模式问题2:重复挂载
开发语言·单例模式·c#
衡石科技21 小时前
HENGSHI ChatBI|不止智能问数,Agentic Analytics 重构经营分析全流程
大数据·重构·数据分析·产品运营·bi
夏霞21 小时前
c# 不支持的目标框架 解决方案
开发语言·c#