|
楼主 |
发表于 2024-4-27 23:49:26
|
显示全部楼层
2. 在 Godot 中封装实用的异步工具函数
我目前最常用的有这些:
- using System;
- using Godot;
- using System.Threading.Tasks;
- public static partial class Async
- {
- // 基于 Godot Timer 的异步等待方法
- public static async Task Wait(Node node, double time, bool physics = false)
- {
- Timer timer = new()
- {
- Autostart = true,
- WaitTime = time,
- ProcessCallback = physics ? Timer.TimerProcessCallback.Physics : Timer.TimerProcessCallback.Idle
- };
- timer.Timeout += timer.QueueFree;
- node.AddChild(timer, false, Node.InternalMode.Front);
- await timer.ToSignal(timer, Timer.SignalName.Timeout);
- }
- // 用于 WaitProcess 方法的辅助节点
- public partial class AsyncProcessTimer : Timer
- {
- public Action<double> Process { get; set; }
- public override void _Process(double delta)
- {
- if (ProcessCallback == TimerProcessCallback.Idle) Process?.Invoke(delta);
- }
- public override void _PhysicsProcess(double delta)
- {
- if (ProcessCallback == TimerProcessCallback.Physics) Process?.Invoke(delta);
- }
- }
- // 在异步等待 Timer 的同时进行 Process
- public static async Task WaitProcess(Node node, double time, Action<double> process, bool physics = false)
- {
- AsyncProcessTimer timer = new()
- {
- Autostart = true,
- WaitTime = time,
- ProcessCallback = physics ? Timer.TimerProcessCallback.Physics : Timer.TimerProcessCallback.Idle,
- Process = process
- };
- timer.Timeout += timer.QueueFree;
- node.AddChild(timer, false, Node.InternalMode.Front);
- await timer.ToSignal(timer, Timer.SignalName.Timeout);
- }
- // 用于 Delegate 方法的辅助节点
- public partial class AsyncDelegateNode : Node
- {
- public Func<double, bool> Action { get; set; }
- public bool Physics { get; set; } = false;
- [Signal]
- public delegate void FinishedEventHandler();
- public void Act(double delta)
- {
- if (Action.Invoke(delta))
- {
- EmitSignal(SignalName.Finished);
- QueueFree();
- }
- }
- public override void _Process(double delta)
- {
- if (!Physics) Act(delta);
- }
- public override void _PhysicsProcess(double delta)
- {
- if (Physics) Act(delta);
- }
- }
- // 异步等待直到给定的 action 返回 true
- public static async Task Delegate(Node node, Func<bool> action, bool physics = false)
- {
- AsyncDelegateNode delegateNode = new()
- {
- Action = (double delta) => action.Invoke(),
- Physics = physics
- };
- node.AddChild(delegateNode, false, Node.InternalMode.Front);
- await delegateNode.ToSignal(delegateNode, AsyncDelegateNode.SignalName.Finished);
- }
- // 在异步等待 Delegate 的同时进行 Process
- public static async Task DelegateProcess(Node node, Func<double, bool> action, bool physics = false)
- {
- AsyncDelegateNode delegateNode = new()
- {
- Action = action,
- Physics = physics
- };
- node.AddChild(delegateNode, false, Node.InternalMode.Front);
- await delegateNode.ToSignal(delegateNode, AsyncDelegateNode.SignalName.Finished);
- }
- }
复制代码
原理和作用查看源代码和相关注释即可,不再赘述
直接拿去用也行,我无所谓 |
|