Advertisement
Inverness

Async MoveToPosition example

Jan 4th, 2014
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.30 KB | None | 0 0
  1. // Cancel any current movement
  2. public bool CancelMoveTask()
  3. {
  4.     if (_moveTask == null)
  5.         return false;
  6.  
  7.     _moveTask = null;
  8.     _moveTaskTokenSource.Cancel();
  9.     _moveTaskTokenSource = null;
  10.  
  11.     return true;
  12. }
  13.  
  14. // Begin moving to the specified position. The task completes when the actor has reached the position,
  15. // the destination is found to be unreachable, or movement is canceled.
  16. public Task<MoveResult> MoveToPosition(Vector2 position)
  17. {
  18.     if (_movement == null)
  19.         return Task.FromResult(MoveResult.Unreachable);
  20.  
  21.     CancelMoveTask();
  22.  
  23.     _moveTaskTokenSource = new CancellationTokenSource();
  24.     _moveTask = MoveToPositionImpl(position, _moveTaskTokenSource.Token);
  25.  
  26.     return _moveTask;
  27. }
  28.  
  29. private async Task<MoveResult> MoveToPositionImpl(Vector2 position, CancellationToken token)
  30. {
  31.     while (!token.IsCancellationRequested)
  32.     {
  33.         if (ReachedPosition(position))
  34.             return MoveResult.Done;
  35.  
  36.         if (IsUnreachable(position))
  37.             return MoveResult.Unreachable;
  38.  
  39.         Vector2 delta = position - Collider.GetCenter(Actor);
  40.         Debug.Assert(_movement.IsLimited); // for now
  41.         _movement.Direction = MovementBehavior.GetDirection(delta);
  42.  
  43.         await AIDispatcher.Yield();
  44.     }
  45.  
  46.     return MoveResult.Canceled;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement