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);
}
相关推荐
根号五4 小时前
JetBrains Rider 使用教程(1)新建解决方案
c#·jetbrains rider
海天鹰5 小时前
C#:接收从打开方式打开的参数
c#
宝桥南山6 小时前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore
风娜6 小时前
用 Claude Code 重构遗留系统:从混乱到有序的实战指南
重构
开开心心_Every6 小时前
文件查重软件批量删除重复文件释放空间
java·开发语言·c#·计算机外设·ocr·excel·perl
波力海苔夹心脆6757 小时前
VisionPro 与 VisionMaster 对比(上):软件定位、开发环境与核心视觉工具对照
图像处理·算法·计算机视觉·c#·视觉检测·个人开发·vp9
疯狂戴夫冒险8 小时前
歇一会 · 久坐休息提醒工具(番茄钟)工具分享
c#
...6228 小时前
VisionMaster 测量模块工具
c#·visionmaster
samble1 天前
从零搭建灌装监控系统(十九):单元测试实战,xUnit + 内存SQLite + 反射测试私有方法
c#·wpf·mvvm·modbus·工业控制
人道领域1 天前
【面试八股速通篇01】锁与并发工具
java·开发语言·面试·c#