Exemple #1
0
        // 开启协程移动,每100毫秒移动一次,并且协程取消的时候会计算玩家真实移动
        // 比方说玩家移动了2500毫秒,玩家有新的目标,这时旧的移动协程结束,将计算250毫秒移动的位置,而不是300毫秒移动的位置
        public async ETTask StartMove(ETCancellationToken cancellationToken)
        {
            Log.Debug("StartMove");
            var transform = Parent.GetComponent <TransformComponent>();

            this.StartPos  = transform.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)
                {
                    transform.position = this.Target;
                }
                else
                {
                    float amount       = (timeNow - this.StartTime) * 1f / this.needTime;
                    transform.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)
                {
                    transform.position = this.Target;
                    break;
                }

                float amount = (timeNow - this.StartTime) * 1f / this.needTime;
                transform.position = Vector3.Lerp(this.StartPos, this.Target, amount);
                //Log.Debug($"{Parent.Id} position={transform.position}");
            }
        }
Exemple #2
0
        public ETTask WaitTillAsync(long tillTime, ETCancellationToken cancellationToken)
        {
            if (TimeHelper.Now() > tillTime)
            {
                return(ETTask.CompletedTask);
            }
            ETTaskCompletionSource tcs   = new ETTaskCompletionSource();
            OnceWaitTimer          timer = EntityFactory.CreateWithParent <OnceWaitTimer, ETTaskCompletionSource>(this, tcs);

            this.timers[timer.Id] = timer;
            AddToTimeId(tillTime, timer.Id);
            cancellationToken.Register(() => { this.Remove(timer.Id); });
            return(tcs.Task);
        }