public async ETTask <bool> WaitAsync(long time, ETCancellationToken cancellationToken) { long tillTime = TimeHelper.Now() + time; if (TimeHelper.Now() > tillTime) { return(true); } ETTaskCompletionSource <bool> tcs = new ETTaskCompletionSource <bool>(); OnceWaitTimer timer = TimerFactory.Create <OnceWaitTimer, ETTaskCompletionSource <bool> >(tcs); this.timers[timer.InstanceId] = timer; AddToTimeId(tillTime, timer.InstanceId); long instanceId = timer.InstanceId; cancellationToken.Register(() => { if (instanceId != timer.InstanceId) { return; } timer.Run(false); this.Remove(timer.InstanceId); }); return(await tcs.Task); }
public async ETTask <bool> WaitTillAsync(long tillTime, ETCancellationToken cancellationToken) { if (TimeHelper.Now() > tillTime) { return(true); } ETTaskCompletionSource <bool> tcs = new ETTaskCompletionSource <bool>(); OnceWaitTimer timer = Entity.CreateWithParent <OnceWaitTimer /*, ETTaskCompletionSource<bool>*/>(this, tcs); this.timers[timer.Id] = timer; AddToTimeId(tillTime, timer.Id); long instanceId = timer.InstanceId; cancellationToken.Register(() => { if (instanceId != timer.InstanceId) { return; } timer.Run(false); this.Remove(timer.Id); }); return(await tcs.Task); }
// 开启协程移动,每100毫秒移动一次,并且协程取消的时候会计算玩家真实移动 // 比方说玩家移动了2500毫秒,玩家有新的目标,这时旧的移动协程结束,将计算250毫秒移动的位置,而不是300毫秒移动的位置 public async ETTask StartMove(ETCancellationToken cancellationToken) { Unit unit = this.GetParent <Unit>(); this.StartPos = unit.Position; this.StartTime = TimeHelper.Now(); float distance = (this.Target - this.StartPos).magnitude; if (Math.Abs(distance) < 0.1f) { return; } this.needTime = (long)(distance / this.Speed * 1000); TimerComponent timerComponent = Game.Scene.GetComponent <TimerComponent>(); // 协程如果取消,将算出玩家的真实位置,赋值给玩家 cancellationToken.Register(() => { long timeNow = TimeHelper.Now(); if (timeNow - this.StartTime >= this.needTime) { unit.Position = this.Target; } else { float amount = (timeNow - this.StartTime) * 1f / this.needTime; unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount); } }); while (true) { await timerComponent.WaitAsync(50, cancellationToken); long timeNow = TimeHelper.Now(); if (timeNow - this.StartTime >= this.needTime) { unit.Position = this.Target; break; } float amount = (timeNow - this.StartTime) * 1f / this.needTime; unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount); } }