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);
}
相关推荐
PfCoder2 小时前
C#中定时器之System.Timers.Timer
c#·.net·visual studio·winform
人工智能AI技术9 小时前
【C#程序员入门AI】本地大模型落地:用Ollama+C#在本地运行Llama 3/Phi-3,无需云端
人工智能·c#
言無咎11 小时前
从规则引擎到任务规划:AI Agent 重构跨境财税复杂账务处理体系
大数据·人工智能·python·重构
程序猿阿伟11 小时前
《非暴力通关的深度策略与挑战重构手册》
重构
MyBFuture13 小时前
C#数组详解:一维二维与交错数组
开发语言·windows·c#·visual studio·vision pro
有来技术14 小时前
ASP.NET Core 权限管理系统(RBAC)设计与实现|vue3-element-admin .NET 后端
vue.js·后端·c#·asp.net·.net
张人玉15 小时前
C#WinFrom中show和ShowDialog的区别
开发语言·microsoft·c#
m0_7482331715 小时前
C#:微软的现代编程利器
开发语言·microsoft·c#
Traced back15 小时前
SQL Server数据自动清理系统最终版(C# WinForms完整源码)
数据库·c#·.net