コード例 #1
0
        //public async Task MoveUnitAsync(IGameUnit unit, IGameMapMovementRoute route)
        //{
        //    await MoveUnitCoroutine(unit, route);
        //}


        /// <summary>
        ///
        /// </summary>
        /// <param name="unit"></param>
        /// <param name="route"></param>
        /// <returns></returns>
        public IEnumerator MoveUnitCoroutine(IGameUnit unit, IGameMapMovementRoute route)
        {
            // Create a container for our move unit
            var moveUnitChangeContainer = new MoveUnitChangeContainer(unit);

            // Quick pre-calculation if we need to do walking damage
            var hasWalkingDamage = unit.GetAttribute(UnitAttribute.WalkingDamage) > 0;

            // Move the unit each step in the given route, excluding None direction steps
            foreach (var routeStep in route.Route.Where(x => x != Direction.None))
            {
                var startPosition   = unit.WorldPosition;
                var directionVector = DirectionHelper.GetDirectionVector(routeStep);
                var targetPosition  = unit.WorldPosition + directionVector;

                // Animate the unit moving this step
                var duration = 0.15f; // 0.15f seconds
                var stepTime = 0f;

                while (stepTime < duration)
                {
                    stepTime          += Time.deltaTime;
                    unit.WorldPosition = Vector3.Lerp(startPosition, targetPosition, stepTime / duration);
                    yield return(null);
                }

                // Animation complete, set the unit position to be the end location
                unit.WorldPosition = targetPosition;
                var newX = unit.MapX;
                var newY = unit.MapY;
                DirectionHelper.ApplyDirection(routeStep, ref newX, ref newY);
                unit.MapX = newX;
                unit.MapY = newY;

                // Apply walking damage to the tiles the unit now occupies
                if (hasWalkingDamage)
                {
                    ApplyWalkingDamage(unit, newX, newY, unit.TileWidth, unit.TileHeight, moveUnitChangeContainer);
                }
            }

            // Final snap the unit to their end map & unity location
            unit.MapX          = route.EndX;
            unit.MapY          = route.EndY;
            unit.WorldPosition = TranslateMapXYToUnityXY(unit.MapX, unit.MapY);
            // And tell them to consume movement for this route
            unit.AddRouteCost(route);
            // Trigger the MoveCompleted event now that we're done animating the move
            OnUnitMoveCompleted(moveUnitChangeContainer);
        }