示例#1
0
 public static Unit FindRemnantWithModifier(Vector3 pos = default(Vector3),string mod="")
 {
     if (pos.IsZero)
         pos = Members.MyHero.NetworkPosition;
     var remnant = ObjectManager.GetEntities<Unit>()
         .Where(
             x =>
                 x.ClassID == ClassID.CDOTA_Unit_Earth_Spirit_Stone && x.Team == Members.MyTeam &&
                 pos.Distance2D(x.NetworkPosition) <= 1500 && x.IsAlive && x.HasModifier(mod)).OrderBy(y => pos.Distance2D(y.NetworkPosition));
     return remnant.FirstOrDefault();
 }
示例#2
0
 public static Unit FindRemnant(Vector3 pos = default(Vector3),float range=200)
 {
     if (pos.IsZero)
         pos = Members.MyHero.NetworkPosition;
     var remnant = ObjectManager.GetEntities<Unit>()
         .Where(
             x =>
                 x.ClassID == ClassID.CDOTA_Unit_Earth_Spirit_Stone && x.Team == Members.MyTeam &&
                 pos.Distance2D(x.NetworkPosition) <= range && x.IsAlive).OrderBy(y => pos.Distance2D(y.NetworkPosition));
     return remnant.FirstOrDefault();
 }
示例#3
0
        private void update_(Vector3 startV3)
        {
            //raycast to test how far we could go..
            Vector3 MaxRangeTestVector3 = MathEx.GetPointAt(startV3, Range, MathEx.ToRadians(DirectionDegrees));

            Vector2 RaycastTestV2;
            //we use main grid providers raycast to test since we are looking at how far we can travel and not if anything is blocking us.
            if (Navigation.MGP.Raycast(startV3.ToVector2(), MaxRangeTestVector3.ToVector2(), out RaycastTestV2))
            {//Set our endpoint at the Hit point
                MaxRangeTestVector3 = RaycastTestV2.ToVector3();
                MaxRangeTestVector3.Z = Navigation.MGP.GetHeight(MaxRangeTestVector3.ToVector2()); //adjust height acordingly!
            }
            Range = Vector3.Distance2D(ref startV3, ref MaxRangeTestVector3);

            //lets see if we can stand here at all?
            if (!Navigation.MGP.CanStandAt(MaxRangeTestVector3))
            {

                //just because raycast set our max range, we need to see if we can use that cell as a walking point!
                if (!Navigation.CanRayCast(startV3, MaxRangeTestVector3, NavCellFlags.AllowWalk))
                {
                    //loop to find a walkable range.
                    float currentRange = Range - 2.5f;
                    float directionRadianFlipped = Navigation.FindDirection(MaxRangeTestVector3, startV3, true);
                    int maxTestAttempts = (int)(currentRange / 2.5f);

                    for (int i = 0; i < maxTestAttempts; i++)
                    {
                        Vector3 newtestPoint = MathEx.GetPointAt(MaxRangeTestVector3, currentRange, directionRadianFlipped);
                        newtestPoint.Z = Navigation.MGP.GetHeight(newtestPoint.ToVector2());//update Z
                        if (Navigation.CanRayCast(startV3, newtestPoint, NavCellFlags.AllowWalk))
                        {
                            MaxRangeTestVector3 = newtestPoint;
                            break;
                        }

                        if (currentRange - 2.5f <= 0f) break;
                        currentRange = -2.5f;
                    }
                    Range = currentRange;
                }

            }

            EndingPoint = MaxRangeTestVector3;
            StartingPoint = startV3;
            Range = startV3.Distance2D(MaxRangeTestVector3); //(float)GridPoint.GetDistanceBetweenPoints(StartingPoint, EndingPoint);
            Center = MathEx.GetPointAt(startV3, Range / 2, MathEx.ToRadians(DirectionDegrees));
        }
示例#4
0
        public override void OnStart()
        {
            _lastMoveResult = MoveResult.Moved;

            float x = MyPos.X + OffsetX;
            float y = MyPos.Y + OffsetY;

            Position = new Vector3(x, y, MainGridProvider.GetHeight(new Vector2(x, y)));

            if (Math.Abs(PathPrecision) < 1f)
            {
                PathPrecision = 10f;
            }
            Logger.Log("OffsetMove Initialized offset x={0} y={1} distance={2:0} position={3}", OffsetX, OffsetY, Position.Distance2D(MyPos), Position);
        }
示例#5
0
 public float Distance2D(SpawnPoint spawn)
 => Vector3.Distance2D(Position, spawn.Position);
示例#6
0
        public override void OnUpdate(int gameTime)
        {
            //UI.ShowSubtitle("vcount: " + ActiveVortexCount + " spawning: " + spawnInProgress + " delay spawn: " + delaySpawn);

            if (ActiveVortexCount < 1)
            {
                if (World.Weather == Weather.ThunderStorm && ScriptThread.GetVar <bool>("spawnInStorm"))
                {
                    if (!spawnInProgress && Game.GameTime - _lastSpawnAttempt > 1000)
                    {
                        if (Probability.GetBoolean(0.05f))
                        {
                            _spawnDelayStartTime = Game.GameTime;

                            _spawnDelayAdditive = Probability.GetInteger(0, 40);

                            Function.Call(Hash.SET_WIND_SPEED, 70.0f); // add suspense :p

                            if (soundEnabled && sirenEnabled && _tornadoWarningSiren != null)
                            {
                                _tornadoWarningSiren.SetVolume(0.6f);

                                _tornadoWarningSiren.Play(true);
                            }

                            if (ScriptThread.GetVar <bool>("notifications"))
                            {
                                Helpers.NotifyWithIcon("Severe Weather Alert", "Tornado Warning issued for Los Santos and Blaine County", "char_milsite");
                            }

                            spawnInProgress = true;
                            delaySpawn      = true;
                        }

                        _lastSpawnAttempt = Game.GameTime;
                    }
                }

                else
                {
                    delaySpawn = false;
                }

                if (delaySpawn)
                {
                    // UI.ShowSubtitle("current: " + (Game.GameTime - _spawnDelayStartTime) + " target: " + (TornadoSpawnDelayBase + _spawnDelayAdditive));

                    if (Game.GameTime - _spawnDelayStartTime > (TornadoSpawnDelayBase + _spawnDelayAdditive))
                    {
                        spawnInProgress = false;
                        delaySpawn      = false;

                        var position = Game.Player.Character.Position + Game.Player.Character.ForwardVector * 100f;

                        CreateVortex(position.Around(150.0f).Around(175.0f));
                    }
                }
            }

            else
            {
                if (_activeVortexList[0].DespawnRequested || Game.Player.IsDead && Function.Call <bool>(Hash.IS_SCREEN_FADED_OUT))
                {
                    RemoveAll();
                }

                else if (soundEnabled)
                {
                    if (_tornadoLowRumble != null)
                    {
                        var distance = Vector3.Distance2D(_activeVortexList[0].Position, GameplayCamera.Position); //attenuation factor

                        var volumeLevel = 1.0f - 1.0f / 800.0f * distance;

                        if (distance < 170.0f)
                        {
                            volumeLevel += 0.087f * (2.219f * volumeLevel);
                        }

                        volumeLevel = volumeLevel <0.0f ? 0.0f : volumeLevel> 1.0f ? 1.0f : volumeLevel;

                        _tornadoLowRumble.SetVolume(volumeLevel);
                    }
                }
            }

            base.OnUpdate(gameTime);
        }
        public void UpdateSearchArea()
        {
            Logger.LogTrivial(this.GetType().Name, "UpdateSearchArea()");

            GameFiber.StartNew(delegate
            {
                GameFiber.Sleep(200);

                heliPilot = new HeliPilot(Vector3.Zero, 0.0f);
                heliPilot.JobFollow(ped);

                while (true)
                {
                    GameFiber.Wait(15000);

                    if (state != EWantedFelonInVehicleState.Searching)
                    {
                        break;
                    }
                    if (!searchZoneBlip.Exists())
                    {
                        break;
                    }

                    if (Vector3.Distance2D(ped.Position, searchZoneBlip.Position) > 415.0f)
                    {
                        if (searchZoneBlip.Exists())
                        {
                            Functions.PlayScannerAudio("REQUEST_GUIDANCE_DISPATCH");

                            Logger.LogTrivial(this.GetType().Name, "SearchArea Updated");

                            GameFiber.Wait(4900);

                            Vector3 position = ped.Position;

                            WildernessCallouts.Common.PlayHeliAudioWithEntityCardinalDirection("OFFICER_INTRO", ped);

                            if (searchZoneBlip.Exists())
                            {
                                searchZoneBlip.Position = ped.Position;
                            }

                            if (ped.IsInAnyVehicle(false))
                            {
                                if (searchZoneBlip.Exists())
                                {
                                    Game.DisplayNotification("~b~Air support: ~w~Suspect vehicle model is ~b~" + ped.CurrentVehicle.Model.Name + "~w~, color ~b~" + ped.CurrentVehicle.GetPrimaryColor().ToFriendlyName().ToLower());
                                }
                                if (searchZoneBlip.Exists())
                                {
                                    Game.DisplayNotification("~b~Air support: ~w~Near ~b~" + position.GetStreetName() + "~w~, in ~b~" + position.GetZoneName());
                                }
                            }
                            else
                            {
                                if (searchZoneBlip.Exists())
                                {
                                    Game.DisplayNotification("~b~Air support: ~w~Suspect is ~b~on foot");
                                }
                                if (searchZoneBlip.Exists())
                                {
                                    Game.DisplayNotification("~b~Air support: ~w~Near ~b~" + position.GetStreetName() + "~w~, in ~b~" + position.GetZoneName());
                                }
                            }
                        }
                    }

                    GameFiber.Yield();
                }
            });
        }
示例#8
0
        /// <summary>
        /// Finds a navigable point in a priority scene
        /// </summary>
        private void FindPrioritySceneTarget()
        {
            if (SceneId == 0 && SceneName == String.Empty)
            {
                return;
            }

            gp.Update();

            if (PrioritySceneTarget != Vector3.Zero)
            {
                return;
            }

            bool foundPriorityScene = false;

            // find any matching priority scenes in scene manager - match by name or SNOId

            List <Scene> PScenes = ZetaDia.Scenes.GetScenes()
                                   .Where(s => s.SceneInfo.SNOId == SceneId).ToList();

            PScenes.AddRange(ZetaDia.Scenes.GetScenes()
                             .Where(s => SceneName.Trim() != String.Empty && s.Name.ToLower().Contains(SceneName.ToLower())).ToList());

            List <Scene> foundPriorityScenes = new List <Scene>();
            Dictionary <int, Vector3> foundPrioritySceneIndex = new Dictionary <int, Vector3>();

            foreach (Scene scene in PScenes)
            {
                if (PriorityScenesInvestigated.Contains(scene.SceneInfo.SNOId))
                {
                    continue;
                }

                foundPriorityScene = true;

                NavZone    navZone = scene.Mesh.Zone;
                NavZoneDef zoneDef = navZone.NavZoneDef;

                Vector2 zoneMin = navZone.ZoneMin;
                Vector2 zoneMax = navZone.ZoneMax;

                Vector3 zoneCenter = GetNavZoneCenter(navZone);

                List <NavCell> NavCells = zoneDef.NavCells.Where(c => c.Flags.HasFlag(NavCellFlags.AllowWalk)).ToList();

                if (!NavCells.Any())
                {
                    continue;
                }

                NavCell bestCell = NavCells.OrderBy(c => GetNavCellCenter(c.Min, c.Max, navZone).Distance2D(zoneCenter)).FirstOrDefault();

                if (bestCell != null)
                {
                    foundPrioritySceneIndex.Add(scene.SceneInfo.SNOId, GetNavCellCenter(bestCell, navZone));
                    foundPriorityScenes.Add(scene);
                }
                else
                {
                    DbHelper.Log(TrinityLogLevel.Normal, LogCategory.ProfileTag, "Found Priority Scene but could not find a navigable point!", true);
                }
            }

            if (foundPrioritySceneIndex.Any())
            {
                KeyValuePair <int, Vector3> nearestPriorityScene = foundPrioritySceneIndex.OrderBy(s => s.Value.Distance2D(myPos)).FirstOrDefault();

                PrioritySceneSNOId   = nearestPriorityScene.Key;
                PrioritySceneTarget  = nearestPriorityScene.Value;
                CurrentPriorityScene = foundPriorityScenes.FirstOrDefault(s => s.SceneInfo.SNOId == PrioritySceneSNOId);

                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.ProfileTag, "Found Priority Scene {0} - {1} Center {2} Distance {3:0}",
                             CurrentPriorityScene.Name, CurrentPriorityScene.SceneInfo.SNOId, PrioritySceneTarget, PrioritySceneTarget.Distance2D(myPos));
            }

            if (!foundPriorityScene)
            {
                PrioritySceneTarget = Vector3.Zero;
            }
        }
示例#9
0
        private void RefreshActorInfo()
        {
            Vector3 myPos = ZetaDia.Me.Position;

            if (_objectiveObject != null && _objectiveObject.IsValid)
            {
                if (QuestTools.EnableDebugLogging)
                {
                    Logger.Log("Found actor {0} {1} {2} of distance {3} from point {4}",
                               _objectiveObject.ActorSNO, _objectiveObject.Name, _objectiveObject.ActorType,
                               _objectiveObject.Position.Distance(_mapMarkerLastPosition), _mapMarkerLastPosition);
                }
            }
            else if (_mapMarkerLastPosition.Distance2D(myPos) <= 200)
            {
                try
                {
                    // Monsters are the actual objective marker
                    _objectiveObject = ZetaDia.Actors.GetActorsOfType <DiaUnit>(true)
                                       .Where(a => a.CommonData != null && a.Position.Distance2D(_mapMarkerLastPosition) <= PathPrecision &&
                                              (a.CommonData.GetAttribute <int>(ActorAttributeType.BountyObjective) != 0))
                                       .OrderBy(a => a.Position.Distance2D(_mapMarkerLastPosition)).FirstOrDefault();

                    if (_objectiveObject == null)
                    {
                        // Portals are not the actual objective but at the marker location
                        _objectiveObject = ZetaDia.Actors.GetActorsOfType <DiaObject>(true)
                                           .Where(o => o != null && o.IsValid && o is GizmoPortal &&
                                                  o.Position.Distance2DSqr(_mapMarkerLastPosition) <= 9f)
                                           .OrderBy(o => o.Distance).FirstOrDefault();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log("Failed trying to find actor {0}", ex);
                }
            }
            else if (_mapMarkerLastPosition != Vector3.Zero && _mapMarkerLastPosition.Distance2D(myPos) <= 90)
            {
                _objectiveObject = ZetaDia.Actors.GetActorsOfType <DiaObject>(true)
                                   .OrderBy(a => a.Position.Distance2D(_mapMarkerLastPosition)).FirstOrDefault();

                if (_objectiveObject != null && _objectiveObject.IsValid)
                {
                    InteractRange = _objectiveObject.CollisionSphere.Radius;
                    Logger.Log("Found Actor from Objective Marker! mapMarkerPos={0} actor={1} {2} {3} {4}",
                               _mapMarkerLastPosition, _objectiveObject.ActorSNO, _objectiveObject.Name, _objectiveObject.ActorType, _objectiveObject.Position);
                }
            }

            if (_objectiveObject != null && _objectiveObject.IsValid)
            {
                if (IsValidObjective())
                {
                    // need to lock on to a specific actor or we'll just keep finding other things near the marker.
                    Logger.Log("Found our Objective Actor! mapMarkerPos={0} actor={1} {2} {3} {4}",
                               _mapMarkerLastPosition, _objectiveObject.ActorSNO, _objectiveObject.Name, _objectiveObject.ActorType, _objectiveObject.Position);
                }
            }

            if (_objectiveObject is GizmoPortal && !IsPortal)
            {
                IsPortal = true;
            }
        }
示例#10
0
        // thanks to Main for the super fast can-stand-at code
        internal static Vector3 MainFindSafeZone(Vector3 origin, bool shouldKite = false, bool isStuck = false, IEnumerable <TrinityCacheObject> monsterList = null, bool avoidDeath = false)
        {
            MainGridProvider.Update();
            Navigator.Clear();

            const float gridSquareSize = 10f;
            const float maxDistance    = 55f;
            const int   maxWeight      = 100;

            double gridSquareRadius = Math.Sqrt((Math.Pow(gridSquareSize / 2, 2) + Math.Pow(gridSquareSize / 2, 2)));

            GridPoint bestPoint = new GridPoint(Vector3.Zero, 0, 0);

            int totalNodes       = 0;
            int nodesCantStand   = 0;
            int nodesZDiff       = 0;
            int nodesGT45Raycast = 0;
            int nodesAvoidance   = 0;
            int nodesMonsters    = 0;
            int pathFailures     = 0;
            int navRaycast       = 0;
            int pointsFound      = 0;

            int worldId = Trinity.Player.WorldID;

            Stopwatch[] timers = Enumerable.Range(0, 12).Select(i => new Stopwatch()).ToArray();

            Vector2 minWorld;

            minWorld.X = origin.X - maxDistance;
            minWorld.Y = origin.Y - maxDistance;

            Point minPoint = MainGridProvider.WorldToGrid(minWorld);

            minPoint.X = Math.Max(minPoint.X, 0);
            minPoint.Y = Math.Max(minPoint.Y, 0);

            Vector2 maxWorld;

            maxWorld.X = origin.X + maxDistance;
            maxWorld.Y = origin.Y + maxDistance;

            Point maxPoint = MainGridProvider.WorldToGrid(maxWorld);

            maxPoint.X = Math.Min(maxPoint.X, MainGridProvider.Width - 1);
            maxPoint.Y = Math.Min(maxPoint.Y, MainGridProvider.Height - 1);

            Point originPos = MainGridProvider.WorldToGrid(origin.ToVector2());

            using (new PerformanceLogger("MainFindSafeZoneLoop"))
            {
                for (int y = minPoint.Y; y <= maxPoint.Y; y++)
                {
                    int searchAreaBasis = y * MainGridProvider.Width;
                    for (int x = minPoint.X; x <= maxPoint.X; x++)
                    {
                        totalNodes++;

                        timers[0].Start();

                        int dx = originPos.X - x;
                        int dy = originPos.Y - y;
                        //if (dx * dx + dy * dy > radius * 2.5 * radius * 2.5)
                        //    continue;

                        // Ignore out of range
                        if (dx * dx + dy * dy > (maxDistance / 2.5f) * (maxDistance / 2.5f))
                        {
                            continue;
                        }
                        // extremely efficient CanStandAt
                        if (!MainGridProvider.SearchArea[searchAreaBasis + x])
                        {
                            nodesCantStand++;
                            continue;
                        }

                        Vector2 xy  = MainGridProvider.GridToWorld(new Point(x, y));
                        Vector3 xyz = Vector3.Zero;

                        if (Trinity.Settings.Combat.Misc.UseNavMeshTargeting)
                        {
                            xyz = new Vector3(xy.X, xy.Y, MainGridProvider.GetHeight(xy));
                        }
                        else
                        {
                            xyz = new Vector3(xy.X, xy.Y, origin.Z + 4);
                        }

                        GridPoint gridPoint = new GridPoint(xyz, 0, origin.Distance(xyz));

                        timers[0].Stop();


                        if (isStuck && gridPoint.Distance > (PlayerMover.TotalAntiStuckAttempts + 2) * 5)
                        {
                            continue;
                        }

                        /*
                         * Check if a square is occupied already
                         */
                        // Avoidance
                        timers[2].Start();
                        if (CacheData.TimeBoundAvoidance.Any(a => xyz.Distance2DSqr(a.Position) - (a.Radius * a.Radius) <= gridSquareRadius * gridSquareRadius))
                        {
                            nodesAvoidance++;
                            continue;
                        }
                        timers[2].Stop();

                        timers[9].Start();
                        // Obstacles
                        if (CacheData.NavigationObstacles.Any(a => xyz.Distance2DSqr(a.Position) - (a.Radius * a.Radius) <= gridSquareRadius * gridSquareRadius))
                        {
                            nodesMonsters++;
                            continue;
                        }
                        timers[9].Stop();

                        timers[10].Start();
                        if (CacheData.NavigationObstacles.Any(a => a.Position.Distance2DSqr(Trinity.Player.Position) < maxDistance * maxDistance &&
                                                              MathUtil.IntersectsPath(a.Position, a.Radius, Trinity.Player.Position, gridPoint.Position)))
                        {
                            pathFailures++;
                        }
                        timers[10].Stop();

                        // Monsters
                        if (shouldKite)
                        {
                            timers[3].Start();
                            double checkRadius = gridSquareRadius;

                            if (CombatBase.PlayerKiteDistance > 0)
                            {
                                checkRadius = gridSquareSize + CombatBase.PlayerKiteDistance;
                            }

                            // Any monster standing in this GridPoint
                            if (CacheData.MonsterObstacles.Any(a => Vector3.Distance(xyz, a.Position) + a.Radius <= checkRadius))
                            {
                                nodesMonsters++;
                                continue;
                            }

                            if (!hasEmergencyTeleportUp)
                            {
                                // Any monsters blocking in a straight line between origin and this GridPoint
                                foreach (CacheObstacleObject monster in CacheData.MonsterObstacles.Where(m =>
                                                                                                         MathEx.IntersectsPath(new Vector3(m.Position.X, m.Position.Y, 0), m.Radius, new Vector3(origin.X, origin.Y, 0), new Vector3(gridPoint.Position.X, gridPoint.Position.Y, 0))
                                                                                                         ))
                                {
                                    nodesMonsters++;
                                    continue;
                                }
                            }
                            timers[3].Stop();
                        }

                        timers[4].Start();
                        if (isStuck && UsedStuckSpots.Any(p => Vector3.Distance(p.Position, gridPoint.Position) <= gridSquareRadius))
                        {
                            continue;
                        }
                        timers[4].Stop();

                        // set base weight
                        if (!isStuck && !avoidDeath)
                        {
                            // e.g. ((100 - 15) / 100) * 100) = 85
                            // e.g. ((100 - 35) / 100) * 100) = 65
                            // e.g. ((100 - 75) / 100) * 100) = 25
                            gridPoint.Weight = ((maxDistance - gridPoint.Distance) / maxDistance) * maxWeight;

                            // Low weight for close range grid points
                            if (shouldKite && gridPoint.Distance < CombatBase.PlayerKiteDistance)
                            {
                                gridPoint.Weight = (int)gridPoint.Distance;
                            }
                        }
                        else
                        {
                            gridPoint.Weight = gridPoint.Distance;
                        }

                        // Boss Areas
                        timers[5].Start();
                        if (UnSafeZone.UnsafeKiteAreas.Any(a => a.WorldId == ZetaDia.CurrentWorldId && Vector3.Distance(a.Position, gridPoint.Position) <= a.Radius))
                        {
                            continue;
                        }
                        timers[5].Stop();

                        if (shouldKite)
                        {
                            // make sure we can raycast to our target
                            //if (!DataDictionary.StraightLinePathingLevelAreaIds.Contains(Trinity.Player.LevelAreaId) &&
                            //    !NavHelper.CanRayCast(gridPoint.Position, Trinity.LastPrimaryTargetPosition))
                            //{
                            //    navRaycast++;
                            //    continue;
                            //}

                            /*
                             * We want to down-weight any grid points where monsters are closer to it than we are
                             */
                            timers[7].Start();
                            foreach (CacheObstacleObject monster in CacheData.MonsterObstacles)
                            {
                                float distFromMonster           = gridPoint.Position.Distance2D(monster.Position);
                                float distFromOrigin            = gridPoint.Position.Distance2D(origin);
                                float distFromOriginToAvoidance = origin.Distance2D(monster.Position);
                                if (distFromOriginToAvoidance < distFromOrigin)
                                {
                                    continue;
                                }

                                if (distFromMonster < distFromOrigin)
                                {
                                    gridPoint.Weight -= distFromOrigin;
                                }
                                else if (distFromMonster > distFromOrigin)
                                {
                                    gridPoint.Weight += distFromMonster;
                                }
                            }
                            timers[7].Stop();

                            timers[8].Start();
                            foreach (CacheObstacleObject avoidance in CacheData.TimeBoundAvoidance)
                            {
                                float distFromAvoidance         = gridPoint.Position.Distance2D(avoidance.Position);
                                float distFromOrigin            = gridPoint.Position.Distance2D(origin);
                                float distFromOriginToAvoidance = origin.Distance2D(avoidance.Position);

                                float health = AvoidanceManager.GetAvoidanceHealthBySNO(avoidance.ActorSNO, 1f);
                                float radius = AvoidanceManager.GetAvoidanceRadiusBySNO(avoidance.ActorSNO, 1f);

                                // position is inside avoidance
                                if (PlayerStatus.CurrentHealthPct < health && distFromAvoidance < radius)
                                {
                                    continue;
                                }

                                // closer to avoidance than it is to player
                                if (distFromOriginToAvoidance < distFromOrigin)
                                {
                                    continue;
                                }

                                if (distFromAvoidance < distFromOrigin)
                                {
                                    gridPoint.Weight -= distFromOrigin;
                                }
                                else if (distFromAvoidance > distFromOrigin)
                                {
                                    gridPoint.Weight += distFromAvoidance;
                                }
                            }
                            timers[8].Stop();
                        }
                        else if (isStuck)
                        {
                            // give weight to points nearer to our destination
                            gridPoint.Weight *= (maxDistance - PlayerMover.LastMoveToTarget.Distance2D(gridPoint.Position)) / maxDistance * maxWeight;
                        }
                        else if (!shouldKite && !isStuck && !avoidDeath) // melee avoidance use only
                        {
                            timers[9].Start();
                            var monsterCount = Trinity.ObjectCache.Count(u => u.IsUnit && u.Position.Distance2D(gridPoint.Position) <= 2.5f);
                            if (monsterCount > 0)
                            {
                                gridPoint.Weight *= monsterCount;
                            }
                            timers[9].Stop();
                        }

                        pointsFound++;

                        if (gridPoint.Weight > bestPoint.Weight && gridPoint.Distance > 1)
                        {
                            bestPoint = gridPoint;
                        }
                    }
                }
            }


            if (isStuck)
            {
                UsedStuckSpots.Add(bestPoint);
            }

            string times = "";

            for (int t = 0; t < timers.Length; t++)
            {
                if (timers[t].IsRunning)
                {
                    timers[t].Stop();
                }
                times += string.Format("{0}/{1:0.0} ", t, timers[t].ElapsedMilliseconds);
            }

            Logger.Log(TrinityLogLevel.Debug, LogCategory.CacheManagement, "Kiting grid found {0}, distance: {1:0}, weight: {2:0}", bestPoint.Position, bestPoint.Distance, bestPoint.Weight);
            Logger.Log(TrinityLogLevel.Debug, LogCategory.CacheManagement,
                       "Kiting grid stats Total={0} CantStand={1} ZDiff {2} GT45Raycast {3} Avoidance {4} Monsters {5} pathFailures {6} navRaycast {7} "
                       + "pointsFound {8} shouldKite={9} isStuck={10} avoidDeath={11} monsters={12} timers={13}",
                       totalNodes,
                       nodesCantStand,
                       nodesZDiff,
                       nodesGT45Raycast,
                       nodesAvoidance,
                       nodesMonsters,
                       pathFailures,
                       navRaycast,
                       pointsFound,
                       shouldKite,
                       isStuck,
                       avoidDeath,
                       monsterList == null ? 0 : monsterList.Count(),
                       times
                       );
            return(bestPoint.Position);
        }
示例#11
0
文件: Windranger.cs 项目: Mej0/a
        public Unit FindShackleTarget(Unit target, Vector3 myPos)
        {
            var shackleDistance = _shackleAbility.GetAbilityData("shackle_distance");
            var angle           = _shackleAbility.GetAbilityData("shackle_angle");
            var speed           = _shackleAbility.GetAbilityData("arrow_speed");

            var distance     = myPos.Distance2D(target);
            var time         = distance / speed * 1000.0f;
            var predictedPos = Prediction.Prediction.PredictPosition(target, (int)time);

            if (distance <= _shackleAbility.GetCastRange() && !target.IsLinkensProtected())
            {
                // check for direct hit with unit behind
                var unitBehind =
                    ObjectManager.GetEntitiesParallel <Unit>()
                    .Any(x => x.IsValid && x != target && x.IsAlive && x.Team != MyHero.Team && !(x is Building) &&
                         x.IsSpawned && x.IsRealUnit() && x.Distance2D(predictedPos) < shackleDistance && x.Distance2D(predictedPos) > x.HullRadius &&
                         RelativeAngleToPositions(myPos, target, x) <= angle);
                if (unitBehind)
                {
                    Log.Debug($"unit behind shackle");
                    return(target);
                }


                // check for tree behind
                var treeBehind =
                    ObjectManager.GetEntitiesParallel <Tree>()
                    .Any(x => x.IsValid && x.IsAlive && x.Team != MyHero.Team &&
                         x.Distance2D(predictedPos) < shackleDistance &&
                         RelativeAngleToPositions(myPos, target, x) <= angle);
                if (treeBehind)
                {
                    Log.Debug($"tree behind shackle");
                    return(target);
                }
            }

            // test if unit infront
            var unitsInfront =
                ObjectManager.GetEntitiesParallel <Unit>()
                .Where(x => x.IsValid && x.IsAlive && x.Team != MyHero.Team && !(x is Building) && !x.IsMagicImmune() && !x.IsLinkensProtected() && _shackleAbility.CanBeCasted(x) && _shackleAbility.CanHit(x) &&
                       x.Distance2D(target) <= shackleDistance && RelativeAngleToPositions(myPos, x, target) <= angle);

            Log.Debug($"in front {unitsInfront.Count()}");
            foreach (var unit in unitsInfront)
            {
                var smallestAngle = ObjectManager.GetEntitiesParallel <Unit>()
                                    .Where(x => x.IsValid && x != unit && x.IsAlive && x.Team != MyHero.Team &&
                                           x.IsSpawned && x.IsRealUnit() && x.Distance2D(unit) < shackleDistance && x.Distance2D(unit) > x.HullRadius &&
                                           RelativeAngleToPositions(myPos, unit, x) <= angle)
                                    .OrderBy(x => RelativeAngleToPositions(myPos, unit, x)).FirstOrDefault();
                if (smallestAngle == target)
                {
                    Log.Debug($"found unit infront {unit.Name}");
                    return(unit);
                }
                else
                {
                    Log.Debug($"not smalled angle {smallestAngle?.Name}");
                }
            }

            return(null);
        }
示例#12
0
 public float Distance(Vector3 position)
 {
     return(position.Distance2D(Unit));
 }
示例#13
0
 private Tree ChainTreePosition(Vector3 endPosition)
 {
     return
         allTrees.Where(
                 x =>
                     x.Distance2D(AbilityOwner) <= GetCastRange()
                     && NavMesh.GetCellFlags(x.Position).HasFlag(NavMeshCellFlags.Tree)
                     && Math.Abs(
                         endPosition.Distance2D(x.Position) + AbilityOwner.Distance2D(x.Position)
                         - AbilityOwner.Distance2D(endPosition)) < 20)
             .OrderBy(x => AbilityOwner.Distance2D(x.Position))
             .ThenBy(x => AbilityOwner.FindRelativeAngle(x.Position))
             .FirstOrDefault();
 }
示例#14
0
文件: Target.cs 项目: IdcNoob/Ensage
 public float GetDistance(Vector3 position)
 {
     return IsVsisible ? position.Distance2D(Hero) : GetPosition().Distance2D(position);
 }
示例#15
0
        private bool CheckPoint(GridPoint point, Vector3 LoSCheckV3, PointCheckingFlags flags)
        {
            //Check blacklisted points and ignored
            if (point.Ignored)
            {
                return(false);
            }

            //Check if this point is in a blocked direction
            if (flags.HasFlag(PointCheckingFlags.BlockedDirection))
            {
                if (FunkyGame.Navigation.CheckPointAgainstBlockedDirection(point))
                {
                    return(false);
                }
            }

            //Create Vector3
            Vector3 pointVectorReturn = (Vector3)point;
            Vector3 pointVector       = pointVectorReturn;
            Vector3 botcurpos         = FunkyGame.Hero.Position;

            //2D Obstacle Navigation Check
            bool ZCheck = false;

            if (this.AreaIsFlat)
            {
                if (flags.HasFlag(PointCheckingFlags.ObstacleOverlap))
                {
                    if (ObjectCache.Obstacles.Values.OfType <CacheServerObject>().Any(obj => ObjectCache.CheckFlag(ObstacleType.Navigation, obj.Obstacletype.Value) && obj.PointInside(point)))
                    {
                        return(false);
                    }
                }

                if (flags.HasFlag(PointCheckingFlags.ObstacleIntersection))
                {
                    if (ObjectCache.Obstacles.Values.OfType <CacheServerObject>().Any(obj => ObjectCache.CheckFlag(ObstacleType.Navigation, obj.Obstacletype.Value) && obj.TestIntersection(botcurpos, point)))
                    {
                        return(false);
                    }
                }

                ZCheck = true;
            }



            //Check if we already within this "point".
            if (botcurpos.Distance2D(pointVector) < 2.5f)
            {
                return(false);
            }

            //3D Obstacle Navigation Check
            if (!ZCheck)
            {
                //Because Z Variance we need to check if we can raycast walk to the location.
                if (!Navigation.CanRayCast(botcurpos, pointVector))
                {
                    return(false);
                }
                if (!Navigation.MGP.CanStandAt(pointVector))
                {
                    return(false);
                }

                if (flags.HasFlag(PointCheckingFlags.ObstacleOverlap))
                {
                    if (ObjectCache.Obstacles.Values.OfType <CacheServerObject>().Any(obj => ObjectCache.CheckFlag(ObstacleType.Navigation, obj.Obstacletype.Value) && obj.PointInside(pointVector)))
                    {
                        return(false);
                    }
                }
                if (flags.HasFlag(PointCheckingFlags.ObstacleIntersection))
                {
                    if (ObjectCache.Obstacles.Values.OfType <CacheServerObject>().Any(obj => ObjectCache.CheckFlag(ObstacleType.Navigation, obj.Obstacletype.Value) && obj.TestIntersection(botcurpos, pointVector)))
                    {
                        return(false);
                    }
                }
            }

            if (!Navigation.CheckVectorFlags(botcurpos, pointVector, flags))
            {
                return(false);
            }

            LastSafespotFound      = pointVectorReturn;
            LastSafeGridPointFound = point.Clone();
            return(true);
        }
示例#16
0
        public async Task <bool> GetToVendorNpc()
        {
            if (WorldManager.ZoneId != ZoneId && WorldManager.ZoneId != 886)
            {
                while (Core.Me.IsCasting)
                {
                    await Coroutine.Sleep(1000);
                }

                if (!ConditionParser.HasAetheryte(AetheryteId))
                {
                    Logger.LogCritical("We can't get to Foundation. You don't have that Aetheryte so do something about it...");
                    TreeRoot.Stop();
                    return(false);
                }

                if (!WorldManager.TeleportById(AetheryteId))
                {
                    Logger.LogCritical($"We can't get to {AetheryteId}. something is very wrong...");
                    TreeRoot.Stop();
                    return(false);
                }

                while (Core.Me.IsCasting)
                {
                    await Coroutine.Sleep(1000);
                }

                if (CommonBehaviors.IsLoading)
                {
                    await Coroutine.Wait(-1, () => !CommonBehaviors.IsLoading);
                }

                await Coroutine.Wait(10000, () => WorldManager.ZoneId == FoundationZoneId);

                await Coroutine.Sleep(3000);

                await Coroutine.Wait(10000, () => GameObjectManager.GetObjectByNPCId(70) != null);

                await Coroutine.Sleep(3000);

                var unit = GameObjectManager.GetObjectByNPCId(70);

                if (!unit.IsWithinInteractRange)
                {
                    var _target = unit.Location;
                    Navigator.PlayerMover.MoveTowards(_target);
                    while (!unit.IsWithinInteractRange)
                    {
                        Navigator.PlayerMover.MoveTowards(_target);
                        await Coroutine.Sleep(100);
                    }

                    Navigator.PlayerMover.MoveStop();
                }

                unit.Target();
                unit.Interact();
                await Coroutine.Sleep(1000);

                await Coroutine.Wait(5000, () => SelectString.IsOpen);

                await Coroutine.Sleep(500);

                if (SelectString.IsOpen)
                {
                    SelectString.ClickSlot(1);
                }

                await Coroutine.Sleep(5000);

                if (CommonBehaviors.IsLoading)
                {
                    await Coroutine.Wait(-1, () => !CommonBehaviors.IsLoading);
                }

                await Coroutine.Sleep(3000);
            }

            if (!(VendorNpc.Location.Distance(Core.Me.Location) > 5f))
            {
                return(Npc.Location.Distance(Core.Me.Location) <= 5f);
            }

            var target = new Vector3(10.58188f, -15.96282f, 163.8702f);

            Navigator.PlayerMover.MoveTowards(target);
            while (target.Distance2D(Core.Me.Location) >= 4)
            {
                Navigator.PlayerMover.MoveTowards(target);
                await Coroutine.Sleep(100);
            }

            Navigator.PlayerMover.MoveStop();

            target = VendorNpc.Location;
            Navigator.PlayerMover.MoveTowards(target);
            while (target.Distance2D(Core.Me.Location) >= 4)
            {
                Navigator.PlayerMover.MoveTowards(target);
                await Coroutine.Sleep(100);
            }

            //await CommonTasks.MoveTo(VendorNpc.Location, "Moving To HandinVendor");

            // await CommonTasks.MoveAndStop(
            //      new MoveToParameters(VendorNpc.Location, "Moving To HandinVendor"), 2f);

            Navigator.PlayerMover.MoveStop();

            return(Npc.Location.Distance(Core.Me.Location) <= 5f);
        }
示例#17
0
        /// <summary>
        ///     Uses prediction to cast given skillshot ability
        /// </summary>
        /// <param name="ability"></param>
        /// <param name="target"></param>
        /// <param name="sourcePosition"></param>
        /// <param name="abilityName"></param>
        /// <param name="soulRing"></param>
        /// <returns>returns true in case of successfull cast</returns>
        public static bool CastSkillShot(
            this Ability ability,
            Unit target,
            Vector3 sourcePosition,
            string abilityName = null,
            Ability soulRing   = null)
        {
            if (!Utils.SleepCheck("CastSkillshot" + ability.Handle))
            {
                return(false);
            }
            var name     = abilityName ?? ability.Name;
            var owner    = ability.Owner as Unit;
            var position = sourcePosition;
            var delay    = ability.GetHitDelay(target, name);

            //AbilityInfo data;
            //if (!AbilityDamage.DataDictionary.TryGetValue(ability, out data))
            //{
            //    data = AbilityDatabase.Find(ability.Name);
            //    AbilityDamage.DataDictionary.Add(ability, data);
            //}
            //delay += data.AdditionalDelay;
            if (target.IsInvul() && !Utils.ChainStun(target, delay, null, false))
            {
                return(false);
            }
            var xyz         = ability.GetPrediction(target, abilityName: name);
            var radius      = ability.GetRadius(name);
            var speed       = ability.GetProjectileSpeed(name);
            var distanceXyz = xyz.Distance2D(position);
            var range       = ability.GetCastRange(name);
            var lion        = name == "lion_impale" ? ability.GetAbilityData("length_buffer") : 0;

            if (!(distanceXyz <= (range + radius + lion)))
            {
                return(false);
            }
            if (distanceXyz > range)
            {
                xyz  = xyz - position;
                xyz /= xyz.Length();
                xyz *= range;
                xyz += position;
            }
            // Console.WriteLine(ability.GetCastRange() + " " + radius);
            if (name.StartsWith("nevermore_shadowraze"))
            {
                xyz = Prediction.SkillShotXYZ(
                    owner,
                    target,
                    (float)((delay + (float)owner.GetTurnTime(xyz)) * 1000),
                    speed,
                    radius);
                //Console.WriteLine(distanceXyz + " " + range + " " + radius);
                if (distanceXyz < (range + radius) && distanceXyz > (range - radius))
                {
                    if (owner.GetTurnTime(xyz) > 0.01)
                    {
                        owner.Move((owner.Position - xyz) * 25 / distanceXyz + xyz);
                        owner.Stop();
                    }
                    else
                    {
                        ability.UseAbility();
                    }
                    return(true);
                }
                return(false);
            }
            if (name == "invoker_ice_wall" && distanceXyz - 50 > 200 && distanceXyz - 50 < 610)
            {
                var mepred = (position - target.Position) * 50 / position.Distance2D(target) + target.Position;
                var v1     = xyz.X - mepred.X;
                var v2     = xyz.Y - mepred.Y;
                var a      = Math.Acos(175 / xyz.Distance(mepred));
                var x1     = v1 * Math.Cos(a) - v2 * Math.Sin(a);
                var y1     = v2 * Math.Cos(a) + v1 * Math.Sin(a);
                var b      = Math.Sqrt((x1 * x1) + (y1 * y1));
                var k1     = x1 * 50 / b;
                var k2     = y1 * 50 / b;
                var vec1   = new Vector3((float)(k1 + mepred.X), (float)(k2 + mepred.Y), mepred.Z);
                if (vec1.Distance2D(mepred) > 0)
                {
                    owner.Move(mepred);
                    owner.Move(vec1, true);
                    ability.UseAbility(true);

                    return(true);
                }
                return(false);
            }
            if (ability.ManaCost > 0 && soulRing.CanBeCasted())
            {
                soulRing.UseAbility();
            }
            ability.UseAbility(xyz);
            return(true);
        }
示例#18
0
        public static void SetNearbyMarkersVisited(Vector3 near, float pathPrecision)
        {
            MiniMapMarker nearestMarker = GetNearestUnvisitedMarker(near);

            if (nearestMarker != null)
            {
                foreach (MiniMapMarker marker in KnownMarkers.Where(m => m.Equals(nearestMarker) && near.Distance2D(m.Position) <= pathPrecision))
                {
                    //DbHelper.Logger.DBLog.InfoFormat(TrinityLogLevel.Normal, LogCategory.ProfileTag, "Setting MiniMapMarker {0} as Visited, within PathPrecision {1:0}", marker.MarkerNameHash, pathPrecision);
                    marker.Visited = true;
                    lastMoveResult = MoveResult.Moved;
                }

                // Navigator will return "ReacheDestination" when it can't fully move to the specified position
                if (lastMoveResult == MoveResult.ReachedDestination)
                {
                    foreach (MiniMapMarker marker in KnownMarkers.Where(m => m.Equals(nearestMarker)))
                    {
                        //DbHelper.Logger.DBLog.InfoFormat(TrinityLogLevel.Normal, LogCategory.ProfileTag, "Setting MiniMapMarker {0} as Visited, MoveResult=ReachedDestination", marker.MarkerNameHash);
                        marker.Visited = true;
                        lastMoveResult = MoveResult.Moved;
                    }
                }

                if (lastMoveResult == MoveResult.PathGenerationFailed)
                {
                    foreach (MiniMapMarker marker in KnownMarkers.Where(m => m.Equals(nearestMarker)))
                    {
                        //DbHelper.Logger.DBLog.InfoFormat(TrinityLogLevel.Normal, LogCategory.ProfileTag, "Unable to navigate to marker, setting MiniMapMarker {0} at {1} as failed", marker.MarkerNameHash, marker.Position);
                        marker.Failed  = true;
                        lastMoveResult = MoveResult.Moved;
                    }
                }
            }
        }
示例#19
0
        public bool RunAround(IAbilityUnit unit, Vector3 target)
        {
            if (this.Unit.SourceUnit.MovementSpeed <= unit.SourceUnit.MovementSpeed)
            {
                return(false);
            }

            var unitPosition   = this.Unit.Position.PredictedByLatency;
            var targetPosition = unit.Position.PredictedByLatency;

            if (target.Distance2D(targetPosition) < 200)
            {
                this.Unit.SourceUnit.Move(unit.SourceUnit.InFront(250));
                return(true);
            }

            if (this.Unit.Position.PredictedByLatency.Distance2D(target)
                < unit.Position.PredictedByLatency.Distance2D(target) ||
                this.Unit.Position.PredictedByLatency.Distance2D(unit.Position.PredictedByLatency) > 250)
            {
                return(false);
            }

            var infront = unit.SourceUnit.InFront(500);

            // infront =
            // this.Target.SourceUnit.InFront(
            // (this.Unit.Position.Current.Distance2D(infront) / this.Unit.SourceUnit.MovementSpeed)
            // * this.Target.SourceUnit.MovementSpeed);
            var backWardsdirection = (targetPosition - infront).Normalized();
            var projectionInfo     = Vector3Extensions.ProjectOn(targetPosition, unitPosition, infront);
            var projectionInfo2    = Vector3Extensions.ProjectOn(
                unitPosition,
                targetPosition + backWardsdirection * (unitPosition.Distance2D(targetPosition) + 200),
                infront);
            var isCloserToFront = unitPosition.Distance2D(infront) + this.Unit.SourceUnit.HullRadius
                                  + unit.SourceUnit.HullRadius + 100 < targetPosition.Distance2D(infront);
            var distanceFromSegment2 = unitPosition.Distance2D(
                Vector2Extensions.ToVector3(projectionInfo2.SegmentPoint));
            var canBlock = (projectionInfo2.IsOnSegment || distanceFromSegment2 < unit.SourceUnit.HullRadius / 2) &&
                           isCloserToFront;

            if (!canBlock &&
                (projectionInfo.IsOnSegment ||
                 targetPosition.Distance2D(Vector2Extensions.ToVector3(projectionInfo.SegmentPoint))
                 < unit.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 20))
            {
                var direction  = (infront - targetPosition).Normalized();
                var direction1 = (infront - targetPosition).Perpendicular().Normalized();
                var direction2 = (targetPosition - infront).Perpendicular().Normalized();

                // Console.WriteLine(direction1 + " " + direction2);
                var position = Pathfinding.ExtendUntilWall(
                    targetPosition,
                    direction1,
                    Math.Max(unit.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 100, distanceFromSegment2),
                    this.Unit.Pathfinder.EnsagePathfinding);

                var position2 = Pathfinding.ExtendUntilWall(
                    targetPosition,
                    direction2,
                    Math.Max(unit.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 100, distanceFromSegment2),
                    this.Unit.Pathfinder.EnsagePathfinding);

                var distance  = unitPosition.Distance2D(position);
                var distance2 = unitPosition.Distance2D(position2);
                if (distance2 < distance)
                {
                    distance = distance2;
                    position = position2;
                }

                if (!isCloserToFront)
                {
                    if (distanceFromSegment2 < unit.SourceUnit.HullRadius + this.Unit.SourceUnit.HullRadius + 50)
                    {
                        infront = Pathfinding.ExtendUntilWall(position, direction, distance + 500, this.Unit.Pathfinder.EnsagePathfinding);
                    }
                    else
                    {
                        infront = Pathfinding.ExtendUntilWall(unitPosition, direction, 500, this.Unit.Pathfinder.EnsagePathfinding);
                    }
                }

                // else
                // {
                // infront = Pathfinding.ExtendUntilWall(unitPosition, direction, 300, this.Pathfinder);
                // }
            }
            else
            {
                return(false);
            }

            this.Unit.SourceUnit.Move(infront);
            return(true);
        }
示例#20
0
        // Special Zig-Zag movement for whirlwind/tempest
        /// <summary>
        /// Finds an optimal position for Barbarian Whirlwind, Monk Tempest Rush, or Demon Hunter Strafe
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="ringDistance"></param>
        /// <param name="randomizeDistance"></param>
        /// <returns></returns>
        internal static Vector3 GetZigZagTarget(Vector3 origin, float ringDistance, bool randomizeDistance = false)
        {
            var     minDistance      = 20f;
            Vector3 myPos            = Player.Position;
            float   distanceToTarget = origin.Distance2D(myPos);

            Vector3 zigZagPoint = origin;

            bool  useTargetBasedZigZag = false;
            float maxDistance          = 25f;
            int   minTargets           = 2;

            if (Trinity.Player.ActorClass == ActorClass.Monk)
            {
                maxDistance          = 20f;
                minTargets           = 3;
                useTargetBasedZigZag = Trinity.Settings.Combat.Monk.TargetBasedZigZag;
            }
            if (Trinity.Player.ActorClass == ActorClass.Barbarian)
            {
                useTargetBasedZigZag = Trinity.Settings.Combat.Barbarian.TargetBasedZigZag;
            }

            int  eliteCount         = ObjectCache.Count(u => u.IsUnit && u.IsBossOrEliteRareUnique);
            bool shouldZigZagElites = ((Trinity.CurrentTarget.IsBossOrEliteRareUnique && eliteCount > 1) || eliteCount == 0);

            if (useTargetBasedZigZag && shouldZigZagElites && !AnyTreasureGoblinsPresent && ObjectCache.Count(o => o.IsUnit) >= minTargets)
            {
                bool attackInAoe  = Trinity.Settings.Combat.Misc.KillMonstersInAoE;
                var  clusterPoint = TargetUtil.GetBestClusterPoint(ringDistance, ringDistance, false, attackInAoe);
                if (clusterPoint.Distance2D(Player.Position) >= minDistance)
                {
                    Logger.Log(LogCategory.Movement, "Returning ZigZag: BestClusterPoint {0} r-dist={1} t-dist={2}", clusterPoint, ringDistance, clusterPoint.Distance2D(Player.Position));
                    return(clusterPoint);
                }


                var zigZagTargetList = new List <TrinityCacheObject>();
                if (attackInAoe)
                {
                    zigZagTargetList =
                        (from u in ObjectCache
                         where u.IsUnit && u.Distance < maxDistance
                         select u).ToList();
                }
                else
                {
                    zigZagTargetList =
                        (from u in ObjectCache
                         where u.IsUnit && u.Distance < maxDistance && !UnitOrPathInAoE(u)
                         select u).ToList();
                }

                if (zigZagTargetList.Count() >= minTargets)
                {
                    zigZagPoint = zigZagTargetList.OrderByDescending(u => u.Distance).FirstOrDefault().Position;
                    if (NavHelper.CanRayCast(zigZagPoint) && zigZagPoint.Distance2D(Player.Position) >= minDistance)
                    {
                        Logger.Log(LogCategory.Movement, "Returning ZigZag: TargetBased {0} r-dist={1} t-dist={2}", zigZagPoint, ringDistance, zigZagPoint.Distance2D(Player.Position));
                        return(zigZagPoint);
                    }
                }
            }

            Random  rndNum             = new Random(int.Parse(Guid.NewGuid().ToString().Substring(0, 8), NumberStyles.HexNumber));
            float   highestWeightFound = float.NegativeInfinity;
            Vector3 bestLocation       = origin;

            // the unit circle always starts at 0 :)
            double min = 0;
            // the maximum size of a unit circle
            double max = 2 * Math.PI;
            // the number of times we will iterate around the circle to find points
            double piSlices = 16;

            // We will do several "passes" to make sure we can get a point that we can least zig-zag to
            // The total number of points tested will be piSlices * distancePasses.Count
            List <float> distancePasses = new List <float>();

            distancePasses.Add(ringDistance * 1 / 2); // Do one loop at 1/2 distance
            distancePasses.Add(ringDistance * 3 / 4); // Do one loop at 3/4 distance
            distancePasses.Add(ringDistance);         // Do one loop at exact distance

            foreach (float distance in distancePasses)
            {
                for (double direction = min; direction < max; direction += (Math.PI / piSlices))
                {
                    // Starting weight is 1
                    float pointWeight = 1f;

                    // Find a new XY
                    zigZagPoint = MathEx.GetPointAt(origin, distance, (float)direction);
                    // Get the Z
                    zigZagPoint.Z = Trinity.MainGridProvider.GetHeight(zigZagPoint.ToVector2());

                    // Make sure we're actually zig-zagging our target, except if we're kiting

                    float targetCircle = CurrentTarget.Radius;
                    if (targetCircle <= 5f)
                    {
                        targetCircle = 5f;
                    }
                    if (targetCircle > 10f)
                    {
                        targetCircle = 10f;
                    }

                    bool intersectsPath = MathUtil.IntersectsPath(CurrentTarget.Position, targetCircle, myPos, zigZagPoint);
                    if (CombatBase.PlayerKiteDistance <= 0 && !intersectsPath)
                    {
                        continue;
                    }

                    // if we're kiting, lets not actualy run through monsters
                    if (CombatBase.PlayerKiteDistance > 0 && CacheData.MonsterObstacles.Any(m => m.Position.Distance(zigZagPoint) <= CombatBase.PlayerKiteDistance))
                    {
                        continue;
                    }

                    // Ignore point if any AoE in this point position
                    if (CacheData.TimeBoundAvoidance.Any(m => m.Position.Distance(zigZagPoint) <= m.Radius && Player.CurrentHealthPct <= AvoidanceManager.GetAvoidanceHealthBySNO(m.ActorSNO, 1)))
                    {
                        continue;
                    }

                    // Make sure this point is in LoS/walkable (not around corners or into a wall)
                    bool canRayCast = !Navigator.Raycast(Player.Position, zigZagPoint);
                    if (!canRayCast)
                    {
                        continue;
                    }

                    float distanceToPoint           = zigZagPoint.Distance2D(myPos);
                    float distanceFromTargetToPoint = zigZagPoint.Distance2D(origin);

                    // Lots of weight for points further away from us (e.g. behind our CurrentTarget)
                    pointWeight *= distanceToPoint;

                    // Add weight for any units in this point
                    int monsterCount = ObjectCache.Count(u => u.IsUnit && u.Position.Distance2D(zigZagPoint) <= Math.Max(u.Radius, 10f));
                    if (monsterCount > 0)
                    {
                        pointWeight *= monsterCount;
                    }

                    //Logger.Log(LogCategory.Movement, "ZigZag Point: {0} distance={1:0} distaceFromTarget={2:0} intersectsPath={3} weight={4:0} monsterCount={5}",
                    //    zigZagPoint, distanceToPoint, distanceFromTargetToPoint, intersectsPath, pointWeight, monsterCount);

                    // Use this one if it's more weight, or we haven't even found one yet, or if same weight as another with a random chance
                    if (pointWeight > highestWeightFound)
                    {
                        highestWeightFound = pointWeight;

                        if (Trinity.Settings.Combat.Misc.UseNavMeshTargeting)
                        {
                            bestLocation = new Vector3(zigZagPoint.X, zigZagPoint.Y, Trinity.MainGridProvider.GetHeight(zigZagPoint.ToVector2()));
                        }
                        else
                        {
                            bestLocation = new Vector3(zigZagPoint.X, zigZagPoint.Y, zigZagPoint.Z + 4);
                        }
                    }
                }
            }
            Logger.Log(LogCategory.Movement, "Returning ZigZag: RandomXY {0} r-dist={1} t-dist={2}", bestLocation, ringDistance, bestLocation.Distance2D(Player.Position));
            return(bestLocation);
        }
示例#21
0
 public float GetDistance(Vector3 position)
 {
     return(IsVsisible ? position.Distance2D(Hero) : GetPosition().Distance2D(position));
 }
示例#22
0
        /*public override void Execute()
         * {
         *  if (Core.TempestHero != null && Core.TempestHero.Hero.IsAlive)
         *  {
         *      if (_sleeper.Sleeping)
         *          return;
         *      if (Core.TempestHero.Orbwalker.GetTarget() == null || Core.TempestHero.Orbwalker.GetTarget().Position.IsZero)
         *      {
         *          ClosestLane = GetClosestLane(Core.TempestHero.Hero);
         *          var lastPoint = ClosestLane.Points[ClosestLane.Points.Count - 1];
         *          ClosestLane.ClosestPosition =
         *              ClosestLane.Points.Where(
         *                      x =>
         *                          x.Distance2D(lastPoint) < Core.TempestHero.Hero.Position.Distance2D(lastPoint) - 300)
         *                  .OrderBy(pos => CheckForDist(pos, Core.TempestHero.Hero))
         *                  .FirstOrDefault();
         *
         *          if (ClosestLane.ClosestPosition != null && !ClosestLane.ClosestPosition.IsZero)
         *          {
         *              if (MenuManager.UseTravels)
         *              {
         *                  var travels = Core.TempestHero.Hero.GetItemById(AbilityId.item_travel_boots) ??
         *                                Core.TempestHero.Hero.GetItemById(AbilityId.item_travel_boots_2);
         *                  if (travels != null && travels.CanBeCasted() && !_sleeper.Sleeping)
         *                  {
         *                      var temp = ClosestLane.Points.ToList();
         *                      temp.Reverse();
         *                      var enemyCreeps =
         *                          EntityManager<Creep>.Entities.Where(x => x.IsValid && x.IsVisible && x.IsAlive && x.Team != ObjectManager.LocalHero.Team);
         *                      Creep creepForTravels = null;
         *
         *                      foreach (var point in temp)
         *                      {
         *                          creepForTravels = EntityManager<Creep>.Entities.FirstOrDefault(
         *                                  allyCreep =>
         *                                      allyCreep.IsValid && allyCreep.IsAlive && allyCreep.Team == ObjectManager.LocalHero.Team &&
         *                                      allyCreep.HealthPercent() > 0.75 &&
         *                                      point.IsInRange(allyCreep.Position, 1500) &&
         *                                      enemyCreeps.Any(z => z.IsInRange(allyCreep, 1500)));
         *                          if (creepForTravels != null)
         *                              break;
         *                      }
         *                      if (creepForTravels != null && creepForTravels.Distance2D(Core.TempestHero.Hero) > 1500)
         *                      {
         *                          travels.UseAbility(creepForTravels);
         *                          _sleeper.Sleep(500);
         *                      }
         *                  }
         *              }
         *
         *
         *              Core.TempestHero.Hero.Move(ClosestLane.ClosestPosition);
         *              try
         *              {
         *                  foreach (var illusion in IllusionManager.GetIllusions)
         *                  {
         *                      illusion.Hero.Move(ClosestLane.ClosestPosition);
         *                  }
         *                  foreach (var necro in NecronomiconManager.GetNecronomicons)
         *                  {
         *                      necro.Necr.Move(ClosestLane.ClosestPosition);
         *                  }
         *              }
         *              catch (Exception e)
         *              {
         *                  Printer.Both("kek "+e.Message);
         *              }
         *              ClosestPosition = ClosestLane.ClosestPosition;
         *          }
         *
         *      }
         *      else if (!_sleeper.Sleeping)
         *      {
         *          if (Core.TempestHero.Spark.CanBeCasted())
         *          {
         *              var target = Core.TempestHero.Orbwalker.GetTarget();
         *              if (target != null)
         *              {
         *                  Printer.Log($"[AutoPushing][Spark][{target.Name}]->{target.Position.PrintVector()}", true);
         *                  if (!target.Position.IsZero)
         *                  {
         *                      Core.TempestHero.Spark.UseAbility(target.Position);
         *                      _sleeper.Sleep(500);
         *                  }
         *              }
         *          }
         *
         *          var itemForPushing = Core.TempestHero.Hero.GetItemById(ItemId.item_mjollnir);
         *          if (itemForPushing != null && itemForPushing.CanBeCasted())
         *          {
         *              var allyCreep =
         *                  EntityManager<Creep>.Entities
         *                      .FirstOrDefault(
         *                          x =>
         *                               x.IsAlive && x.Team == ObjectManager.LocalHero.Team &&
         *                              x.IsInRange(Core.TempestHero.Hero, 500) && x.HealthPercent() <= 0.92 &&
         *                              x.IsMelee);
         *              if (allyCreep != null)
         *              {
         *                  itemForPushing.UseAbility(allyCreep);
         *                  _sleeper.Sleep(500);
         *              }
         *          }
         *          itemForPushing = Core.TempestHero.Hero.GetItemById(ItemId.item_manta);
         *
         *          if (itemForPushing != null && itemForPushing.CanBeCasted())
         *          {
         *              itemForPushing.UseAbility();
         *              _sleeper.Sleep(500);
         *          }
         *
         *          itemForPushing = Core.TempestHero.Hero.GetItemById(ItemId.item_necronomicon) ??
         *                           Core.TempestHero.Hero.GetItemById(ItemId.item_necronomicon_2) ??
         *                           Core.TempestHero.Hero.GetItemById(ItemId.item_necronomicon_3);
         *          if (itemForPushing != null && itemForPushing.CanBeCasted())
         *          {
         *              itemForPushing.UseAbility();
         *              _sleeper.Sleep(500);
         *          }
         *          if (Core.TempestHero.Orbwalker.GetTarget() is Tower)
         *          {
         *              var field = Core.TempestHero.MagneticField;
         *              if (field.CanBeCasted())
         *              {
         *                  var pos =
         *                  (Core.TempestHero.Orbwalker.GetTarget().NetworkPosition -
         *                   Core.TempestHero.Hero.NetworkPosition).Normalized();
         *                  pos *= (280 + 150);
         *                  pos = Core.TempestHero.Orbwalker.GetTarget().NetworkPosition - pos;
         *                  field.UseAbility(pos);
         *                  _sleeper.Sleep(1000);
         *              }
         *          }
         *      }
         *      if (MenuManager.AutoPushingTargetting)
         *      {
         *          var enemyHero =
         *              Heroes.GetByTeam(ObjectManager.LocalHero.GetEnemyTeam())
         *                  .FirstOrDefault(x => Core.TempestHero.Hero.IsValidOrbwalkingTarget(x));
         *          if (enemyHero != null)
         *          {
         *              //OrderManager.ChangeOrder(OrderManager.Orders.SparkSpamTempest);
         *              Core.Target = enemyHero;
         *              MenuManager.TempestCombo.SetValue(new KeyBind(MenuManager.TempestCombo.GetValue<KeyBind>().Key,
         *                  KeyBindType.Toggle, true));
         *              Core.Target = enemyHero;
         *          }
         *      }
         *      _sleeper.Sleep(250);
         *  }
         *  else
         *  {
         *      if (_sleeper.Sleeping)
         *          return;
         *      _sleeper.Sleep(400);
         *      foreach (var illusion in IllusionManager.GetIllusions.Where(x => x.Orbwalker.GetTarget() == null))
         *      {
         *          ClosestLane = GetClosestLane(illusion.Hero);
         *          var pushPos = ClosestLane.Points.LastOrDefault();
         *          illusion.Hero.Move(pushPos);
         *      }
         *      foreach (var necro in NecronomiconManager.GetNecronomicons.Where(x => x.Orbwalker.GetTarget() == null))
         *      {
         *          ClosestLane = GetClosestLane(necro.Necr);
         *          var pushPos = ClosestLane.Points.LastOrDefault();
         *          necro.Necr.Move(pushPos);
         *      }
         *  }
         * }*/

        /*private Lane GetClosestLane(Unit hero)
         * {
         *  if (PushLaneSelector.GetInstance().Loaded)
         *  {
         *      var selected = PushLaneSelector.GetInstance().GetSelectedLane;
         *      if (!string.IsNullOrEmpty(selected))
         *      {
         *          selected = selected.Substring(5);
         *          if (selected != "Pushing")
         *          {
         *              if (selected.Equals(TopLane.Name))
         *              {
         *                  return TopLane;
         *              }
         *              if (selected.Equals(MidLane.Name))
         *              {
         *                  return MidLane;
         *              }
         *              if (selected.Equals(BotLane.Name))
         *              {
         *                  return BotLane;
         *              }
         *          }
         *      }
         *  }
         *  var pos = hero.Position;
         *  var top =
         *      TopLane.Points.OrderBy(x => pos.Distance2D(x)).FirstOrDefault();
         *  var mid =
         *      MidLane.Points.OrderBy(x => pos.Distance2D(x)).FirstOrDefault();
         *  var bot =
         *      BotLane.Points.OrderBy(x => pos.Distance2D(x)).FirstOrDefault();
         *  if (CheckForDist(top, hero) < CheckForDist(mid, hero))
         *      if (CheckForDist(top, hero) < CheckForDist(bot, hero))
         *      {
         *          return TopLane;
         *      }
         *      else
         *      {
         *          return BotLane;
         *      }
         *  if (CheckForDist(mid, hero) < CheckForDist(bot, hero))
         *  {
         *      return MidLane;
         *  }
         *  return BotLane;
         * }*/

        private float CheckForDist(Vector3 pos, Unit hero)
        {
            return(pos.Distance2D(hero.Position));
        }
示例#23
0
        private async Task <bool> FindNode(bool retryCenterHotspot = true)
        {
            if (Node != null)
            {
                return(false);
            }

            StatusText = Localization.ExGather_SearchForNodes;

            while (Behaviors.ShouldContinue)
            {
                IEnumerable <GatheringPointObject> nodes =
                    GameObjectManager.GetObjectsOfType <GatheringPointObject>().Where(gpo => gpo.CanGather).ToArray();

                if (GatherStrategy == GatherStrategy.TouchAndGo && HotSpots != null)
                {
                    if (GatherObjects != null)
                    {
                        nodes = nodes.Where(gpo => GatherObjects.Contains(gpo.EnglishName, StringComparer.InvariantCultureIgnoreCase));
                    }

                    foreach (GatheringPointObject node in
                             nodes.Where(gpo => HotSpots.CurrentOrDefault.WithinHotSpot2D(gpo.Location))
                             .OrderBy(gpo => gpo.Location.Distance2D(ExProfileBehavior.Me.Location))
                             .Skip(1))
                    {
                        if (!Blacklist.Contains(node.ObjectId, BlacklistFlags.Interact))
                        {
                            Blacklist.Add(
                                node,
                                BlacklistFlags.Interact,
                                TimeSpan.FromSeconds(18),
                                Localization.ExGather_SkipFurthestNodes);
                        }
                    }
                }

                nodes = nodes.Where(gpo => !Blacklist.Contains(gpo.ObjectId, BlacklistFlags.Interact));

                if (FreeRange)
                {
                    nodes = nodes.Where(gpo => gpo.Distance2D(ExProfileBehavior.Me.Location) < Radius);
                }
                else
                {
                    if (HotSpots != null)
                    {
                        nodes = nodes.Where(gpo => HotSpots.CurrentOrDefault.WithinHotSpot2D(gpo.Location));
                    }
                }

                // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                if (GatherObjects != null)
                {
                    Node =
                        nodes.OrderBy(
                            gpo =>
                            GatherObjects.FindIndex(i => string.Equals(gpo.EnglishName, i, StringComparison.InvariantCultureIgnoreCase)))
                        .ThenBy(gpo => gpo.Location.Distance2D(ExProfileBehavior.Me.Location))
                        .FirstOrDefault(gpo => GatherObjects.Contains(gpo.EnglishName, StringComparer.InvariantCultureIgnoreCase));
                }
                else
                {
                    Node = nodes.OrderBy(gpo => gpo.Location.Distance2D(ExProfileBehavior.Me.Location)).FirstOrDefault();
                }

                if (Node == null)
                {
                    if (HotSpots != null)
                    {
                        Vector3 myLocation = ExProfileBehavior.Me.Location;

                        float distanceToFurthestVisibleGameObject =
                            GameObjectManager.GameObjects.Select(o => o.Location.Distance2D(myLocation))
                            .OrderByDescending(o => o)
                            .FirstOrDefault();

                        float distanceToFurthestVectorInHotspot = myLocation.Distance2D(HotSpots.CurrentOrDefault)
                                                                  + HotSpots.CurrentOrDefault.Radius;

                        if (myLocation.Distance2D(HotSpots.CurrentOrDefault) > Radius && GatherStrategy == GatherStrategy.GatherOrCollect &&
                            retryCenterHotspot && distanceToFurthestVisibleGameObject <= distanceToFurthestVectorInHotspot)
                        {
                            Logger.Verbose(Localization.ExGather_DistanceObject + distanceToFurthestVisibleGameObject);
                            Logger.Verbose(Localization.ExGather_DistanceHotSpot + distanceToFurthestVectorInHotspot);

                            Logger.Warn(
                                Localization.ExGather_NoAvailableNode);
                            await HotSpots.CurrentOrDefault.XYZ.MoveTo(radius : Radius, name : HotSpots.CurrentOrDefault.Name);

                            retryCenterHotspot = false;
                            await Coroutine.Yield();

                            continue;
                        }

                        if (!await ChangeHotSpot())
                        {
                            retryCenterHotspot = false;
                            await Coroutine.Yield();

                            continue;
                        }
                    }

                    if (FreeRange && !FreeRangeConditional())
                    {
                        await Coroutine.Yield();

                        isDone = true;
                        return(true);
                    }

                    return(true);
                }

                Blacklist.BlacklistEntry entry = Blacklist.GetEntry(Node.ObjectId);
                if (entry != null && entry.Flags.HasFlag(BlacklistFlags.Interact))
                {
                    Logger.Warn(Localization.ExGather_NodeBlacklist);

                    if (await Coroutine.Wait(entry.Length, () =>
                                             entry.IsFinished || Node.Location.Distance2D(ExProfileBehavior.Me.Location) > Radius) || Core.Player.IsDead
                        )
                    {
                        if (!entry.IsFinished)
                        {
                            Node = null;
                            Logger.Info(Localization.ExGather_NodeReset);
                            return(false);
                        }
                    }

                    Logger.Info(Localization.ExGather_NodeBlacklistRemoved);
                }

                Logger.Info(Localization.ExGather_NodeSet + Node);

                if (HotSpots == null)
                {
                    MovementManager.SetFacing2D(Node.Location);
                }

                if (Poi.Current.Unit != Node)
                {
                    Poi.Current = new Poi(Node, PoiType.Gather);
                }

                return(true);
            }

            return(true);
        }
示例#24
0
 public static bool IsWithinRange(Vector3 position, float range = 12f)
 {
     return(position != Vector3.Zero && !(position.Distance2D(ZetaDia.Me.Position) > range));
 }
示例#25
0
        private static void Monk_MaintainTempestRush()
        {
            if (!Monk_TempestRushReady())
            {
                return;
            }

            if (PlayerStatus.IsInTown || Zeta.CommonBot.Logic.BrainBehavior.IsVendoring)
            {
                return;
            }

            if (TownRun.IsTryingToTownPortal())
            {
                return;
            }

            if (TimeSinceUse(SNOPower.Monk_TempestRush) > 150)
            {
                return;
            }

            bool shouldMaintain = false;
            bool nullTarget     = CurrentTarget == null;

            if (!nullTarget)
            {
                // maintain for everything except items, doors, interactables... stuff we have to "click" on
                switch (CurrentTarget.Type)
                {
                case GObjectType.Unit:
                case GObjectType.Gold:
                case GObjectType.Avoidance:
                case GObjectType.Barricade:
                case GObjectType.Destructible:
                case GObjectType.Globe:
                {
                    if (Settings.Combat.Monk.TROption == TempestRushOption.TrashOnly &&
                        (TargetUtil.AnyElitesInRange(40f) || CurrentTarget.IsBossOrEliteRareUnique))
                    {
                        shouldMaintain = false;
                    }
                    else
                    {
                        shouldMaintain = true;
                    }
                }
                break;
                }
            }
            else
            {
                shouldMaintain = true;
            }

            if (Settings.Combat.Monk.TROption != TempestRushOption.MovementOnly && GilesUseTimer(SNOPower.Monk_TempestRush) && shouldMaintain)
            {
                Vector3 target = LastTempestRushLocation;

                string locationSource = "LastLocation";

                //if (CurrentTarget != null && GilesNavHelper.CanRayCast(PlayerStatus.CurrentPosition, CurrentTarget.Position))
                //{
                //    locationSource = "Current Target Position";
                //    target = CurrentTarget.Position;
                //}

                if (target.Distance2D(ZetaDia.Me.Position) <= 1f)
                {
                    // rrrix edit: we can't maintain here
                    return;

                    //locationSource = "ZigZag";
                    //target = FindZigZagTargetLocation(target, 23f);
                }

                if (target == Vector3.Zero)
                {
                    return;
                }

                float DestinationDistance = target.Distance2D(ZetaDia.Me.Position);

                //target = MathEx.CalculatePointFrom(target, PlayerStatus.CurrentPosition, aimPointDistance);
                target = TargetUtil.FindTempestRushTarget();

                if (DestinationDistance > 10f && NavHelper.CanRayCast(ZetaDia.Me.Position, target))
                {
                    Monk_TempestRushStatus(String.Format("Using Tempest Rush to maintain channeling, source={0}, V3={1} dist={2:0}", locationSource, target, DestinationDistance));

                    var usePowerResult = ZetaDia.Me.UsePower(SNOPower.Monk_TempestRush, target, CurrentWorldDynamicId, -1);
                    if (usePowerResult)
                    {
                        dictAbilityLastUse[SNOPower.Monk_TempestRush] = DateTime.Now;
                    }
                }
            }
        }
示例#26
0
        private void RefreshActorInfo()
        {
            Vector3 myPos = ZetaDia.Me.Position;

            if (_interactObject != null && !_interactObject.IsValid)
            {
                _interactObject = null;
            }

            if ((_interactObject == null || (_interactObject != null && !_interactObject.IsValid)) && ActorId != 0)
            {
                _interactObject = ZetaDia.Actors.GetActorsOfType <DiaObject>(true)
                                  .Where(o => o.IsValid && o.ActorSNO == ActorId && ActorWithinRangeOfMarker(o))
                                  .OrderBy(DistanceToMapMarker)
                                  .FirstOrDefault();
            }
            if (_interactObject != null && _interactObject.IsValid)
            {
                if (QuestTools.EnableDebugLogging)
                {
                    Logger.Debug("Found actor {0} {1} {2} of distance {3} from point {4}",
                                 _interactObject.ActorSNO, _interactObject.Name, _interactObject.ActorType, _interactObject.Position.Distance(_mapMarkerLastPosition), _mapMarkerLastPosition);
                }
            }
            else if (ActorId != 0 && Position != Vector3.Zero && _position.Distance(ZetaDia.Me.Position) <= PathPrecision)
            {
                // ActorId defined, use object closest to player
                _interactObject = ZetaDia.Actors.GetActorsOfType <DiaObject>(true).Where(o => o.IsValid && o.ActorSNO == ActorId &&
                                                                                         o.Position.Distance2D(Position) <= PathPrecision).OrderBy(o => o.Distance).FirstOrDefault();
            }
            else if (ActorId != 0 && _mapMarkerLastPosition != Vector3.Zero && _mapMarkerLastPosition.Distance(myPos) <= PathPrecision)
            {
                // No ActorID defined, using Marker position to find actor closest to player
                _interactObject = ZetaDia.Actors.GetActorsOfType <DiaObject>(true).Where(o => o != null && o.IsValid && o.ActorSNO == ActorId &&
                                                                                         o.Position.Distance2D(_mapMarkerLastPosition) <= PathPrecision).OrderBy(o => o.Distance).FirstOrDefault();
            }
            else if (ActorId == 0 && _mapMarkerLastPosition != Vector3.Zero && _mapMarkerLastPosition.Distance2D(myPos) <= 90)
            {
                // No ActorId defined, but we've found the marker, find object closest to marker position
                _interactObject = ZetaDia.Actors.GetActorsOfType <DiaObject>(true)
                                  .Where(a => a.Position.Distance2D(_mapMarkerLastPosition) <= MaxSearchDistance)
                                  .OrderBy(a => a.Position.Distance2D(_mapMarkerLastPosition)).FirstOrDefault();

                if (_interactObject != null)
                {
                    InteractRange = _interactObject.CollisionSphere.Radius;
                    Logger.Debug("Found Actor from Map Marker! mapMarkerPos={0} actor={1} {2} {3} {4}",
                                 _mapMarkerLastPosition, _interactObject.ActorSNO, _interactObject.Name, _interactObject.ActorType, _interactObject.Position);
                }
            }


            if (_interactObject == null && _mapMarkerLastPosition.Distance(ZetaDia.Me.Position) < PathPrecision)
            {
                Logger.Debug("Could not find an actor {0} within range {1} from point {2}",
                             ActorId, PathPrecision, _mapMarkerLastPosition);
            }

            if (_interactObject is GizmoPortal && !IsPortal)
            {
                IsPortal = true;
            }
        }
示例#27
0
        public static async Task <bool> Run()
        {
            PluginContainer plugin = PluginManager.Plugins.Where(p => p.Plugin.Name == "SideStep" || p.Plugin.Name == "回避").First();

            IEnumerable <BattleCharacter> check = GameObjectManager.GetObjectsOfType <BattleCharacter>().Where(r => r.CastingSpellId != 0 && !r.IsMe && r.Distance() < 50 && (r.CastingSpellId == 15723 || r.CastingSpellId == 13520 || r.CastingSpellId == 13844));

            IEnumerable <BattleCharacter> check2 = GameObjectManager.GetObjectsOfType <BattleCharacter>().Where(r => r.CastingSpellId != 0 && !r.IsMe && r.Distance() < 50 && (r.CastingSpellId == 13552));

            IEnumerable <BattleCharacter> sC3 = GameObjectManager.GetObjectsOfType <BattleCharacter>().Where(r => !r.IsMe && r.Distance() < 50 && r.NpcId == 8146);  //73BOSS3

            //过独木桥     BOSS 3
            if (check.Any() == true && sC3.First().Location.Distance2D(Core.Me.Location) >= 10)
            {
                //读条中断
                if (Core.Me.IsCasting)
                {
                    ActionManager.StopCasting();
                }

                await Coroutine.Sleep(3000);

                Logging.Write(Colors.Aquamarine, $"过独木桥");
                //过桥
                Vector3 Location = new Vector3("-142.8355,-144.5264,-232.6624");
                while (Location.Distance2D(Core.Me.Location) > 0.2)
                {
                    Logging.Write(Colors.Aquamarine, $"远点距离:{Location.Distance2D(Core.Me.Location)}");
                    Navigator.PlayerMover.MoveTowards(Location);
                    await Coroutine.Sleep(30);
                }
                Location = new Vector3("-140.8284,-144.5366,-246.1443");
                while (Location.Distance2D(Core.Me.Location) > 0.2)
                {
                    Logging.Write(Colors.Aquamarine, $"远点距离:{Location.Distance2D(Core.Me.Location)}");
                    Navigator.PlayerMover.MoveTowards(Location);
                    await Coroutine.Sleep(30);
                }
                Location = new Vector3("-130.1889,-144.5366,-242.384");
                while (Location.Distance2D(Core.Me.Location) > 0.2)
                {
                    Logging.Write(Colors.Aquamarine, $"远点距离:{Location.Distance2D(Core.Me.Location)}");
                    Navigator.PlayerMover.MoveTowards(Location);
                    await Coroutine.Sleep(30);
                }
                Location = new Vector3("-114.455,-144.5366,-244.2632");
                while (Location.Distance2D(Core.Me.Location) > 0.2)
                {
                    Logging.Write(Colors.Aquamarine, $"远点距离:{Location.Distance2D(Core.Me.Location)}");
                    Navigator.PlayerMover.MoveTowards(Location);
                    await Coroutine.Sleep(30);
                }
                Location = new Vector3("-125.6857,-144.5238,-249.264");
                while (Location.Distance2D(Core.Me.Location) > 0.2)
                {
                    Logging.Write(Colors.Aquamarine, $"远点距离:{Location.Distance2D(Core.Me.Location)}");
                    Navigator.PlayerMover.MoveTowards(Location);
                    await Coroutine.Sleep(30);
                }
                Location = new Vector3("-122.5055,-144.5192,-258.3726");
                while (Location.Distance2D(Core.Me.Location) > 0.2)
                {
                    Logging.Write(Colors.Aquamarine, $"远点距离:{Location.Distance2D(Core.Me.Location)}");
                    Navigator.PlayerMover.MoveTowards(Location);
                    await Coroutine.Sleep(30);
                }
                Location = new Vector3("-128.1084,-144.5226,-258.0896");
                while (Location.Distance2D(Core.Me.Location) > 1)
                {
                    Logging.Write(Colors.Aquamarine, $"远点距离:{Location.Distance2D(Core.Me.Location)}");
                    Navigator.PlayerMover.MoveTowards(Location);
                    await Coroutine.Sleep(100);
                }
            }

            if (check2.Any() == true)
            {
                Logging.Write(Colors.Aquamarine, $"背对");

                Vector3 Location = new Vector3("-128.474,-144.5366,-243.2417");
                while (Location.Distance2D(Core.Me.Location) > 1)
                {
                    Logging.Write(Colors.Aquamarine, $"背对:{Location.Distance2D(Core.Me.Location)}");
                    Navigator.PlayerMover.MoveTowards(Location);
                    await Coroutine.Sleep(100);
                }

                Navigator.PlayerMover.MoveStop();
                await Coroutine.Sleep(3000);
            }

            /// 2183, 4708, 4709, 6975, 10384, 10385, 10386, 11768, 13920, 15796, 16227, 16973, 16974, 16975, 17199      :: Savage Swipe
            /// 4526, 11014, 13786, 15794, 16234                                                                         :: Unfinal Sting
            /// 5174, 5175, 13547, 13548                                                                                 :: Corrosive Bile
            /// 5176, 13549                                                                                              :: Malaise
            /// 5177, 13550                                                                                              :: Bile Bombardment
            /// 5178, 5179, 13952, 13953                                                                                 :: Flailing Tentacles
            /// 13514                                                                                                    :: Venom Shower
            /// 13551                                                                                                    :: Toad Choir
            /// 15788, 16837                                                                                             :: Pollen Corona
            HashSet <uint> spellCastIds = new HashSet <uint>()
            {
                2183, 4526, 4708, 4709, 5174, 5175, 5176, 5177, 5178, 5179,
                6975, 10384, 10385, 10386, 11014, 11768, 13514, 13547, 13548,
                13549, 13550, 13551, 13786, 13920, 13952, 13953, 15788, 15794,
                15796, 16227, 16234, 16837, 16973, 16974, 16975, 17199
            };
            bool spellCasting = GameObjectManager.GetObjectsOfType <BattleCharacter>(true, false).Where(obj =>
                                                                                                        spellCastIds.Contains(obj.CastingSpellId) && obj.Distance() < 50).Count() > 0;

            if (spellCasting)
            {
                await Helpers.GetClosestAlly.Follow();
            }

            if (Core.Target != null)
            {
                IEnumerable <BattleCharacter> sC = GameObjectManager.GetObjectsOfType <BattleCharacter>().Where(
                    r => !r.IsMe && r.Distance() < 50 && r.NpcId == 8141
                    );  //73BOSS1
                IEnumerable <BattleCharacter> sC1 = GameObjectManager.GetObjectsOfType <BattleCharacter>().Where(
                    r => !r.IsMe && r.Distance() < 50 && r.NpcId == 8146
                    );  //73BOSS3

                // 73boss 1 移动
                if (sC.Any() == true)
                {
                    if (plugin != null)
                    {
                        if (plugin.Enabled == true)
                        {
                            plugin.Enabled = false;
                        }
                    }

                    Logging.Write(Colors.Aquamarine, $"boss1");
                    BattleCharacter spellCaster = sC.First();


                    if (spellCaster != null && spellCaster.Name == Core.Target.Name)
                    {
                        BattleCharacter Obj = GameObjectManager.GetObjectsOfType <BattleCharacter>(true).Where(r =>
                                                                                                               (r.NpcId == 729 || r.NpcId == 8378 || // "雅·修特拉"
                                                                                                                                                     //r.NpcId == 1492 ||                       // "于里昂热"
                                                                                                                                                     //r.NpcId == 4130 ||                       // "阿尔菲诺"
                                                                                                                r.NpcId == 5239 ||                   // "阿莉塞"
                                                                                                                r.NpcId == 8889 ||                   // 琳
                                                                                                                r.Name == "雅·修特拉" ||
                                                                                                                r.Name == "阿莉塞" ||
                                                                                                                r.Name == "敏菲利亚" ||
                                                                                                                r.Name == "琳") &&
                                                                                                               r.IsDead == false
                                                                                                               ).OrderBy(r => r.Distance()).First();

                        //当距离大于跟随距离 再处理跟随
                        if (Obj.Location.Distance2D(Core.Me.Location) >= 0.2)
                        {
                            //读条中断
                            if (Core.Me.IsCasting)
                            {
                                ActionManager.StopCasting();
                            }

                            // 选中跟随最近的队友
                            Obj.Target();

                            Logging.Write(Colors.Aquamarine, $"队友{Obj.Name}距离:{Obj.Location.Distance2D(Core.Me.Location)}");

                            while (Obj.Location.Distance2D(Core.Me.Location) >= 0.2)
                            {
                                Navigator.PlayerMover.MoveTowards(Obj.Location);
                                await Coroutine.Sleep(50);
                            }
                            Navigator.PlayerMover.MoveStop();
                            await Coroutine.Sleep(50);

                            return(true);
                        }
                    }
                }
                if (sC1.Any() == true)
                {
                    if (plugin != null)
                    {
                        if (plugin.Enabled == true)
                        {
                            plugin.Enabled = false;
                        }
                    }
                }
            }

            return(false);
        }
示例#28
0
        public float GetEvadeTime(Vector3 position)
        {
            var distance = Math.Max(position.Distance2D(this.Position) - this.Radius, 0);

            return((this.EndCastTime + this.ActivationDelay + (distance / this.Speed)) - Game.RawGameTime);
        }
示例#29
0
        /// <summary>
        ///     The cast combo.
        /// </summary>
        /// <returns>
        ///     The <see cref="bool" />.
        /// </returns>
        private static bool CastCombo()
        {
            var canCancel = Orbwalking.CanCancelAnimation();
            var manaCheck = Menu.Item("manaSlider").GetValue <Slider>().Value < me.Mana;

            if (!Utils.SleepCheck("casting") || !me.CanCast() || !target.IsVisible || !canCancel)
            {
                return(false);
            }

            if (manaCheck && abyssalBlade != null && abyssalBlade.IsValid && menuValue.IsEnabled(abyssalBlade.Name) &&
                abyssalBlade.CanBeCasted() && targetDistance <= (350 + hullsum) && Utils.SleepCheck("abyssal"))
            {
                var canUse = Utils.ChainStun(target, turnTime + 0.1 + Game.Ping / 1000, null, false);
                if (canUse)
                {
                    abyssalBlade.UseAbility(target);
                    Utils.Sleep(turnTime * 1000 + 100 + Game.Ping, "abyssal");
                    Utils.Sleep(turnTime * 1000 + 50, "move");
                    Utils.Sleep(
                        turnTime * 1000 + 100
                        + (Math.Max(targetDistance - hullsum - abyssalBlade.CastRange, 0) / me.MovementSpeed) * 1000,
                        "casting");
                    Utils.Sleep(turnTime * 1000 + 200, "CHAINSTUN_SLEEP");
                    return(true);
                }
            }

            if (manaCheck && scytheOfVyse != null && scytheOfVyse.IsValid && menuValue.IsEnabled(scytheOfVyse.Name) &&
                scytheOfVyse.CanBeCasted() && targetDistance <= (scytheOfVyse.CastRange + hullsum) &&
                Utils.SleepCheck("hex"))
            {
                var canUse = Utils.ChainStun(target, turnTime + 0.1 + Game.Ping / 1000, null, false);
                if (canUse)
                {
                    scytheOfVyse.UseAbility(target);
                    Utils.Sleep(turnTime * 1000 + 100 + Game.Ping, "hex");
                    Utils.Sleep(turnTime * 1000 + 50, "move");
                    Utils.Sleep(
                        turnTime * 1000 + 100
                        + (Math.Max(targetDistance - hullsum - scytheOfVyse.CastRange, 0) / me.MovementSpeed) * 1000,
                        "casting");
                    Utils.Sleep(turnTime * 1000 + 200, "CHAINSTUN_SLEEP");
                    return(true);
                }
            }

            if (manaCheck && menuValue.IsEnabled(earthshock.Name) && earthshock.CanBeCasted() && Utils.SleepCheck("Q") &&
                ((me.Mana - earthshock.ManaCost) > overpower.ManaCost || !overpower.CanBeCasted()))
            {
                var radius = earthshock.GetAbilityData("shock_radius");
                var pos    = target.Position
                             + target.Vector3FromPolarAngle() * ((Game.Ping / 1000 + 0.3f) * target.MovementSpeed);

                if (mePosition.Distance(pos) < targetDistance)
                {
                    pos = target.Position;
                }

                if (mePosition.Distance2D(pos) <= radius &&
                    (abyssalBlade == null || !abyssalBlade.CanBeCasted() || mePosition.Distance2D(pos) > 200) &&
                    (scytheOfVyse == null || !scytheOfVyse.CanBeCasted() || mePosition.Distance2D(pos) > 200))
                {
                    var canUse = Utils.ChainStun(target, 0.3 + Game.Ping / 1000, null, false);
                    if (canUse)
                    {
                        earthshock.UseAbility();
                        Utils.Sleep(earthshockCastPoint * 1000 + Game.Ping, "Q");
                        Utils.Sleep(earthshockCastPoint * 1000, "casting");
                        return(true);
                    }
                }
                else if (Utils.SleepCheck("moveCloser"))
                {
                    me.Move(pos);
                    Utils.Sleep(200, "moveCloser");
                    return(true);
                }
            }

            // Console.WriteLine(blink != null);
            if (blink != null && menuValue.IsEnabled(blink.Name) && blink.CanBeCasted() && targetDistance > 400 &&
                targetDistance < (blinkRange + hullsum * 2 + me.AttackRange) && Utils.SleepCheck("blink"))
            {
                var position = target.Position;
                if (target.NetworkActivity != NetworkActivity.Idle)
                {
                    position = target.Position + target.Vector3FromPolarAngle() * (hullsum + me.AttackRange);
                    if (mePosition.Distance(position) < targetDistance)
                    {
                        position = target.Position;
                    }
                }

                var dist = position.Distance2D(mePosition);
                if (dist > blinkRange)
                {
                    position = (position - mePosition) * (blinkRange - 1) / position.Distance2D(me) + mePosition;
                }

                blink.UseAbility(position);
                mePosition = position;
                Utils.Sleep(turnTime * 1000 + 100 + Game.Ping, "blink");
                Utils.Sleep(turnTime * 1000 + 50, "move");
                Utils.Sleep(turnTime * 1000, "casting");
                return(true);
            }

            const int Radius    = 300;
            var       canAttack = !target.IsInvul() && !target.IsAttackImmune() && me.CanAttack();

            if (!canAttack)
            {
                return(false);
            }

            if (manaCheck && menuValue.IsEnabled(overpower.Name) && overpower.CanBeCasted() && Utils.SleepCheck("W") &&
                !(earthshock.CanBeCasted() && Utils.ChainStun(target, 0.3 + Game.Ping / 1000, null, false)))
            {
                if (mePosition.Distance2D(target) <= (Radius + hullsum))
                {
                    overpower.UseAbility();
                    Utils.Sleep(overpowerCastPoint * 1000 + Game.Ping, "W");
                    Utils.Sleep(overpowerCastPoint * 1000, "casting");
                    return(true);
                }
            }

            if (!menuValue.IsEnabled(enrage.Name) || !enrage.CanBeCasted() || !Utils.SleepCheck("R"))
            {
                return(false);
            }

            if (!(mePosition.Distance2D(target) <= (Radius + hullsum)))
            {
                return(false);
            }

            enrage.UseAbility();
            Utils.Sleep(100 + Game.Ping, "R");
            Utils.Sleep(100, "casting");
            return(true);
        }
示例#30
0
        public void MoveTowards(Vector3 vMoveToTarget)
        {
            if (FunkyGame.Hero.Class == null)
            {
                Logger.DBLog.InfoFormat("Bot did not properly initilize, stopping bot!");
                BotMain.Stop(false, "Bot Init Failure");
                return;
            }

            #region LogStucks
            // The below code is to help profile/routine makers avoid waypoints with a long distance between them.
            // Long-distances between waypoints is bad - it increases stucks, and forces the DB nav-server to be called.

            //if (vLastMoveTo==Vector3.Zero) vLastMoveTo=vMoveToTarget;

            if (vMoveToTarget != vLastMoveTo)
            {
                vLastMoveTo = vMoveToTarget;

                if (FunkyBaseExtension.Settings.Debugging.LogStuckLocations)
                {
                    vLastMoveTo          = vMoveToTarget;
                    bLastWaypointWasTown = false;

                    float fDistance = Vector3.Distance(vMoveToTarget, vLastMoveTo);
                    // Logger.DBLog.InfoFormat if not in town, last waypoint wasn't FROM town, and the distance is >200 but <2000 (cos 2000+ probably means we changed map zones!)
                    if (!ZetaDia.IsInTown && !bLastWaypointWasTown && fDistance >= 200 & fDistance <= 2000)
                    {
                        if (!hashDoneThisVector.Contains(vMoveToTarget))
                        {
                            // Logger.DBLog.InfoFormat it
                            string outputPath = FolderPaths.LoggingFolderPath + @"\Stucks.log";

                            FileStream LogStream = File.Open(outputPath, FileMode.Append, FileAccess.Write, FileShare.Read);
                            using (StreamWriter LogWriter = new StreamWriter(LogStream))
                            {
                                LogWriter.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture) + ":");
                                LogWriter.WriteLine("Profile Name=" + ProfileManager.CurrentProfile.Name);
                                LogWriter.WriteLine("'From' Waypoint=" + vLastMoveTo + ". 'To' Waypoint=" + vMoveToTarget + ". Distance=" + fDistance.ToString(CultureInfo.InvariantCulture));
                            }
                            //LogStream.Close();
                            hashDoneThisVector.Add(vMoveToTarget);
                        }
                    }
                }

                if (ZetaDia.IsInTown)
                {
                    bLastWaypointWasTown = true;
                }
            }

            #endregion



            // Make sure GilesTrinity doesn't want us to avoid routine-movement
            if (FunkyGame.Targeting.Cache.DontMove)
            {
                return;
            }

            // Store player current position
            Vector3 vMyCurrentPosition = ZetaDia.Me.Position;

            //Check GPC entry (backtracking cache) -- only when not in town!
            if (BackTrackCache.EnableBacktrackGPRcache && !ZetaDia.IsInTown)
            {
                if (DateTime.Now.Subtract(LastCombatPointChecked).TotalMilliseconds > 1250)
                {
                    if (BackTrackCache.cacheMovementGPRs.Count == 0)
                    {
                        BackTrackCache.StartNewGPR(vMyCurrentPosition);
                    }
                    else
                    {                    //Add new point only if distance is 25f difference
                        if (BackTrackCache.cacheMovementGPRs.Count == 1)
                        {
                            if (BackTrackCache.cacheMovementGPRs[0].CreationVector.Distance(vMyCurrentPosition) >= BackTrackCache.MinimumRangeBetweenMovementGPRs)
                            {
                                BackTrackCache.StartNewGPR(vMyCurrentPosition);
                            }
                        }
                        else
                        {
                            //Only if no GPCs currently are less than 20f from us..
                            if (!BackTrackCache.cacheMovementGPRs.Any(GPC => GPC.CreationVector.Distance(vMyCurrentPosition) < BackTrackCache.MinimumRangeBetweenMovementGPRs))
                            {
                                BackTrackCache.StartNewGPR(vMyCurrentPosition);
                            }
                        }
                    }
                    //Reset Timer
                    LastCombatPointChecked = DateTime.Now;
                }
            }

            //Special cache for skipping locations visited.
            //if (FunkyBaseExtension.Settings.Debugging.SkipAhead)
            //{
            //	SkipAheadCache.RecordSkipAheadCachePoint();

            //	//Check if our current profile behavior is ExploreDungeon tag.
            //	if (FunkyGame.Profile.CurrentProfileBehaviorType == Profile.ProfileBehaviorTypes.ExploreDungeon) //&& !SkipAheadCache.LevelAreaIDsIgnoreSkipping.Contains(FunkyGame.Hero.iCurrentLevelID))
            //	{
            //		//Check if DungeonExplorer and Current Node are valid. (only when there is more than one node in current route)
            //		if (Navigation.CurrentDungeonExplorer != null && Navigation.DungeonExplorerCurrentNode != null && Navigation.CurrentDungeonExplorer.CurrentRoute.Count > 1)
            //		{
            //			if (Navigation.NP.CurrentPath != null && Navigation.NP.CurrentPath.Count > 0)
            //			{
            //				var destination = Navigation.NP.CurrentPath.Last();
            //				float distance = destination.Distance2D(Navigation.DungeonExplorerCurrentNode.NavigableCenter);
            //				//Logger.DBLog.InfoFormat("[Funky] Distance from CurrentNode Center == {0}", distance);
            //				if (distance <= 5f)
            //				{
            //					//Check if our target position is within skip ahead cache.
            //					if (SkipAheadCache.CheckPositionForSkipping(destination))
            //					{
            //						Logger.DBLog.Info("[Funky] Marking Node as Visited! (PlayerMover)");
            //						Logger.DBLog.DebugFormat("[Funky] {0}", Navigation.PrintDungeonExplorerNode(Navigation.DungeonExplorerCurrentNode));
            //						Navigation.DungeonExplorerCurrentNode.Visited = true;
            //					}
            //				}
            //			}
            //		}
            //	}
            //}

            // Store distance to current moveto target
            float fDistanceFromTarget;

            #region Unstucker
            // Do unstuckery things
            if (FunkyBaseExtension.Settings.Debugging.EnableUnstucker)
            {
                // Store the "real" (not anti-stuck) destination
                vOldMoveToTarget = vMoveToTarget;

                // See if we can reset the 10-limit unstuck counter, if >120 seconds since we last generated an unstuck location
                if (iTotalAntiStuckAttempts > 1 && DateTime.Now.Subtract(timeStartedUnstuckMeasure).TotalSeconds >= 120)
                {
                    iTotalAntiStuckAttempts = 1;
                    iTimesReachedStuckPoint = 0;
                    vSafeMovementLocation   = Vector3.Zero;
                }

                // See if we need to, and can, generate unstuck actions
                if (DateTime.Now.Subtract(timeCancelledUnstuckerFor).TotalSeconds > iCancelUnstuckerForSeconds && UnstuckChecker(vMyCurrentPosition))
                {
                    // Record the time we last apparently couldn't move for a brief period of time
                    timeLastReportedAnyStuck = DateTime.Now;
                    // See if there's any stuck position to try and navigate to generated by random mover
                    vSafeMovementLocation = UnstuckHandler(vMyCurrentPosition, vOldMoveToTarget);
                    if (vSafeMovementLocation == Vector3.Zero)
                    {
                        return;
                    }
                }

                // See if we can clear the total unstuckattempts if we haven't been stuck in over 6 minutes.
                if (DateTime.Now.Subtract(timeLastReportedAnyStuck).TotalSeconds >= 360)
                {
                    iTimesReachedMaxUnstucks = 0;
                }

                // Did we have a safe point already generated (eg from last loop through), if so use it as our current location instead
                if (vSafeMovementLocation != Vector3.Zero)
                {
                    // Set our current movement target to the safe point we generated last cycle
                    vMoveToTarget = vSafeMovementLocation;
                }

                // Get distance to current destination
                fDistanceFromTarget = Vector3.Distance(vMyCurrentPosition, vMoveToTarget);

                // Remove the stuck position if it's been reached, this bit of code also creates multiple stuck-patterns in an ever increasing amount
                if (vSafeMovementLocation != Vector3.Zero && fDistanceFromTarget <= 3f)
                {
                    vSafeMovementLocation = Vector3.Zero;
                    iTimesReachedStuckPoint++;
                    // Do we want to immediately generate a 2nd waypoint to "chain" anti-stucks in an ever-increasing path-length?
                    if (iTimesReachedStuckPoint <= iTotalAntiStuckAttempts)
                    {
                        FunkyGame.Navigation.AttemptFindSafeSpot(out vSafeMovementLocation, Vector3.Zero, FunkyBaseExtension.Settings.Plugin.AvoidanceFlags);
                        vMoveToTarget = vSafeMovementLocation;
                    }
                    else
                    {
                        Logger.DBLog.DebugFormat("[Funky] Clearing old route and trying new path find to: " + vOldMoveToTarget.ToString());
                        // Reset the path and allow a whole "New" unstuck generation next cycle
                        iTimesReachedStuckPoint = 0;
                        // And cancel unstucking for 9 seconds so DB can try to navigate
                        iCancelUnstuckerForSeconds = (9 * iTotalAntiStuckAttempts);
                        if (iCancelUnstuckerForSeconds < 20)
                        {
                            iCancelUnstuckerForSeconds = 20;
                        }
                        timeCancelledUnstuckerFor = DateTime.Now;
                        Navigator.Clear();
                        Navigator.MoveTo(vOldMoveToTarget, "original destination", false);
                        return;
                    }
                }
            }
            #endregion



            //Prioritize "blocking" objects.
            if (!FunkyGame.Hero.bIsInTown)
            {
                FunkyGame.Navigation.ObstaclePrioritizeCheck();
            }



            #region MovementAbilities
            // See if we can use abilities like leap etc. for movement out of combat, but not in town and only if we can raycast.
            if (FunkyBaseExtension.Settings.General.OutOfCombatMovement && !ZetaDia.IsInTown && !FunkyGame.IsInNonCombatBehavior)
            {
                Skill   MovementPower;
                Vector3 MovementVector = FunkyGame.Hero.Class.FindOutOfCombatMovementPower(out MovementPower, vMoveToTarget);
                if (MovementVector != Vector3.Zero)
                {
                    ZetaDia.Me.UsePower(MovementPower.Power, MovementVector, FunkyGame.Hero.CurrentWorldDynamicID);
                    MovementPower.OnSuccessfullyUsed();
                    return;
                }
            }             // Allowed to use movement powers to move out-of-combat?
            #endregion


            //Send Movement Command!
            if (vMyCurrentPosition.Distance2D(vMoveToTarget) > 1f)
            {
                ZetaDia.Me.UsePower(SNOPower.Walk, vMoveToTarget, FunkyGame.Hero.CurrentWorldDynamicID);
            }
        }
示例#31
0
 public override float GetRemainingTime(Hero hero = null)
 {
     return(Math.Min(1.8f, startPosition.Distance2D(endPosition) / 600) - (Game.RawGameTime - StartCast));
 }
示例#32
0
        public double UpdateWeight(out int monstercount, out int avoidcount, ref List <int> UsedRAGUIDs, bool ResetIndex = false)
        {
            monstercount = 0;
            avoidcount   = 0;
            if (ResetIndex)
            {
                LastIndexUsed = 0;
            }

            OccupiedObjects.Clear();

            Vector3 sectorCenter = this.Center;
            //Get the Diagonal Length between start and end, multiply by 2.5 since each point represents an area of 5f than Divide the total by 2 for the radius range.
            double range = GridPoint.GetDistanceBetweenPoints(this.StartPoint, this.CornerPoint);

            int TotalGridPoints = this.ContainedPoints.Count;

            this.ThisWeight = 0d;


            //We use 2D Distance and subtract the obstacles radius
            IEnumerable <CacheObstacle> obstaclesContained = ObjectCache.Obstacles.Values
                                                             .Where(obs => Math.Max(0f, sectorCenter.Distance2D(obs.Position) - obs.Radius) <= range);

            double maxaverage = ObjectCache.Objects.MaximumHitPointAverage;

            if (obstaclesContained.Any())
            {
                //reset weight
                this.ThisWeight = 0;

                //copy SectorPoints
                //GridPoint[] SectorPoints=new GridPoint[this.ContainedPoints.Count];
                //this.ContainedPoints.CopyTo(SectorPoints);

                List <GridPoint> NonNavPoints = new List <GridPoint>();

                foreach (CacheObstacle item in obstaclesContained)
                {
                    OccupiedObjects.Add(item.RAGUID);

                    if (item is CacheServerObject)
                    {
                        //Monsters should add 10% of its weight
                        //if (item.Obstacletype.Value==ObstacleType.Monster)
                        //{
                        //	if (FunkyBaseExtension.Settings.Fleeing.EnableFleeingBehavior&& FunkyGame.Targeting.Environment.FleeTrigeringRAGUIDs.Contains(item.RAGUID))
                        //	{

                        //	}

                        //}
                        if (item.Obstacletype.Value == ObstacleType.ServerObject)
                        {
                            //give +1 to weight
                            this.ThisWeight++;
                        }
                    }
                    else if (item is CacheAvoidance)
                    {
                        if (!UsedRAGUIDs.Contains(item.RAGUID))
                        {
                            AvoidanceType thisAvoidanceType = ((CacheAvoidance)item).AvoidanceType;
                            if (AvoidanceCache.IgnoringAvoidanceType(thisAvoidanceType))
                            {
                                continue;
                            }
                            AvoidanceValue AV = FunkyBaseExtension.Settings.Avoidance.Avoidances[(int)thisAvoidanceType];

                            avoidcount++;
                            float BaseWeight = AV.Weight;

                            //if ((AvoidanceType.ArcaneSentry|AvoidanceType.Dececrator|AvoidanceType.MoltenCore|AvoidanceType.TreeSpore).HasFlag(thisAvoidanceType))
                            //	 BaseWeight=1f;
                            //else
                            //	 BaseWeight=0.5f;

                            this.ThisWeight += (BaseWeight / FunkyGame.Hero.dCurrentHealthPct);

                            UsedRAGUIDs.Add(item.RAGUID);
                        }
                    }
                }

                ////Now add a base score for non-nav points. (25 being 100% non-navigable)
                //int PointMultiplier=(25/TotalGridPoints);
                //int RemainingPoints=SectorPoints.Length;
                //this.ThisWeight+=25-(RemainingPoints*PointMultiplier);


                //Logger.DBLog.InfoFormat("Weight assigned to this sector {0}. \r\n"
                //+"Total Points {1} with {2} Remaining points Valid!", this.ThisWeight, this.ContainedPoints.Count, SectorPoints.Length);
            }

            return(this.ThisWeight);

            //(Total Points / Non-Navigable Points Ratio)
        }
示例#33
0
        private static void Game_OnUpdate(EventArgs args)
        {
            var me = ObjectManager.LocalHero;

            if (!Game.IsInGame || me == null || Game.IsWatchingGame)
            {
                return;
            }
            activated = Menu.Item("Push key").GetValue <KeyBind>().Active;
            if (activated && !Game.IsPaused)
            {
                var unit = ObjectManager.GetEntities <Unit>().Where(creep =>
                                                                    (creep.ClassId == ClassId.CDOTA_BaseNPC_Creep_Neutral ||
                                                                     creep.ClassId == ClassId.CDOTA_BaseNPC_Additive ||
                                                                     creep.ClassId == ClassId.CDOTA_BaseNPC_Creep ||
                                                                     creep.ClassId == ClassId.CDOTA_Unit_Broodmother_Spiderling ||
                                                                     creep.IsIllusion) &&
                                                                    creep.IsAlive &&
                                                                    creep.NetworkActivity != NetworkActivity.Move &&
                                                                    creep.Team == me.Team &&
                                                                    creep.IsControllable &&
                                                                    creep.IsValid).ToList();
                if (unit.Count == 0)
                {
                    return;
                }

                Unit        fount = ObjectManager.GetEntities <Unit>().FirstOrDefault(x => x.Team == me.Team && x.ClassId == ClassId.CDOTA_Unit_Fountain);
                List <Unit> tower = ObjectManager.GetEntities <Unit>().Where(x => x.Team != me.Team && x.ClassId == ClassId.CDOTA_BaseNPC_Tower).ToList();

                for (int i = 0; i < unit.Count(); ++i)
                {
                    Vector3 Mid = GetClosestToVector(mid, unit[i]);
                    Vector3 Top = GetClosestToVector(top, unit[i]);
                    Vector3 Bot = GetClosestToVector(bot, unit[i]);
                    if (me.Distance2D(unit[i]) <= range)
                    {
                        return;
                    }
                    var v =
                        ObjectManager.GetEntities <Hero>()
                        .Where(x => x.Team != me.Team && x.IsAlive && x.IsVisible && !x.IsIllusion)
                        .ToList();

                    if (Mid.Distance2D(unit[i]) <= 4000)
                    {
                        for (int x = 0; x < mid.Count(); ++x)
                        {
                            var b = mid[x];
                            if (
                                unit[i].Distance2D(fount) + 170 < b.Distance2D(fount) && unit[i].Distance2D(b) <= 4000 && Utils.SleepCheck(unit[i].Handle.ToString()))
                            {
                                unit[i].Attack(b); Utils.Sleep(1500, unit[i].Handle.ToString());
                            }
                        }
                    }
                    if (Bot.Distance2D(unit[i]) <= 4000)
                    {
                        for (int x = 0; x < bot.Count(); ++x)
                        {
                            var b = bot[x];
                            if (
                                unit[i].Distance2D(fount) + 170 < b.Distance2D(fount) && unit[i].Distance2D(b) <= 4000 && Utils.SleepCheck(unit[i].Handle.ToString()))
                            {
                                unit[i].Attack(b); Utils.Sleep(1500, unit[i].Handle.ToString());
                            }
                        }
                    }
                    if (Top.Distance2D(unit[i]) <= 4000)
                    {
                        for (int x = 0; x < top.Count(); ++x)
                        {
                            var b = top[x];
                            if (
                                unit[i].Distance2D(fount) + 170 < b.Distance2D(fount) && unit[i].Distance2D(b) <= 4000 && Utils.SleepCheck(unit[i].Handle.ToString()))
                            {
                                unit[i].Attack(b); Utils.Sleep(1500, unit[i].Handle.ToString());
                            }
                        }
                    }
                }
            }
        }
示例#34
0
        public async Task <bool> HandInItem(uint itemId, int index, int job)
        {
            //GameObjectType.EventNpc;

            if (!HWDSupply.Instance.IsOpen && Npc == null)
            {
                await GetToNpc();
            }

            if (!HWDSupply.Instance.IsOpen && Npc.Location.Distance(Core.Me.Location) > 5f)
            {
                // NpcId = Npc.NpcId;
                // await CommonTasks.MoveAndStop(
                //     new MoveToParameters(Npc.Location, "Moving To HandinVendor"), 2f);
                //await CommonTasks.MoveAndStop(Npc.Location, "Moving To HandinVendor");

                var _target = new Vector3(10.58188f, -15.96282f, 163.8702f);
                Navigator.PlayerMover.MoveTowards(_target);
                while (_target.Distance2D(Core.Me.Location) >= 4)
                {
                    Navigator.PlayerMover.MoveTowards(_target);
                    await Coroutine.Sleep(100);
                }

                Navigator.PlayerMover.MoveStop();

                _target = Npc.Location;
                Navigator.PlayerMover.MoveTowards(_target);
                while (_target.Distance2D(Core.Me.Location) >= 4)
                {
                    Navigator.PlayerMover.MoveTowards(_target);
                    await Coroutine.Sleep(100);
                }

                Navigator.PlayerMover.MoveStop();


                Navigator.PlayerMover.MoveStop();
                await Coroutine.Sleep(500);
            }

            if (!HWDSupply.Instance.IsOpen)
            {
                //NpcId = GameObjectManager.GameObjects.First(i => i.EnglishName == EnglishName).NpcId;
                Npc.Interact();
                await Coroutine.Wait(5000, () => HWDSupply.Instance.IsOpen || Talk.DialogOpen);

                await Coroutine.Sleep(1000);

                while (Talk.DialogOpen)
                {
                    Talk.Next();
                    await Coroutine.Wait(5000, () => !Talk.DialogOpen);
                }

                await Coroutine.Sleep(1000);
            }

            if (HWDSupply.Instance.IsOpen)
            {
                if (HWDSupply.Instance.ClassSelected != job)
                {
                    HWDSupply.Instance.ClassSelected = job;
                    await Coroutine.Sleep(1000);
                }
                //var item = InventoryManager.FilledSlots.FirstOrDefault(i => i.RawItemId == itemId);

                foreach (var item in InventoryManager.FilledSlots.Where(i => i.RawItemId == itemId))
                {
                    HWDSupply.Instance.ClickItem(index);

                    await Coroutine.Wait(5000, () => Request.IsOpen);

                    await Coroutine.Sleep(1000);

                    item.Handover();
                    await Coroutine.Sleep(200);

                    await Coroutine.Wait(5000, () => Request.HandOverButtonClickable);

                    Request.HandOver();
                    await Coroutine.Wait(2000, () => SelectYesno.IsOpen);

                    if (SelectYesno.IsOpen)
                    {
                        SelectYesno.Yes();
                        await Coroutine.Sleep(2000);
                    }
                }
            }

            return(false);
        }
示例#35
0
        }         // OnClose

        public void Combo()
        {
            if (!Menu.Item("enabled").IsActive() || Game.IsChatOpen || Time.Enabled)
            {
                return;
            }
            Me = ObjectManager.LocalHero;

            Q = Me.Spellbook.SpellQ;
            W = Me.Spellbook.SpellW;
            R = Me.Spellbook.SpellR;

            Leans    = Me.FindItem("item_aether_lens");
            Urn      = Me.FindItem("item_urn_of_shadows");
            Dagon    = Me.Inventory.Items.FirstOrDefault(x => x.Name.Contains("item_dagon"));
            Ethereal = Me.FindItem("item_ethereal_blade");
            Shiva    = Me.FindItem("item_shivas_guard");
            Glimmer  = Me.FindItem("item_glimmer_cape");
            Vail     = Me.FindItem("item_veil_of_discord");
            Orchid   = Me.FindItem("item_orchid") ?? Me.FindItem("item_bloodthorn");
            Abyssal  = Me.FindItem("item_abyssal_blade");
            Atos     = Me.FindItem("item_rod_of_atos");
            Bkb      = Me.FindItem("item_black_king_bar");
            Mail     = Me.FindItem("item_blade_mail");
            Lotus    = Me.FindItem("item_lotus_orb");
            Active   = Game.IsKeyDown(Menu.Item("Combo Key").GetValue <KeyBind>().Key);
            var v = ObjectManager.GetEntities <Hero>().Where(x => x.Team != Me.Team && x.IsAlive && x.IsVisible && !x.IsIllusion && !x.IsMagicImmune()).ToList();

            if (Active && Menu.Item("Skills").GetValue <AbilityToggler>().IsEnabled(W.Name))
            {
                if (Me.HasModifier("modifier_pudge_rot") && v.Count(x => x.Distance2D(Me) <= W.GetCastRange() + Me.HullRadius) == 0)
                {
                    W.ToggleAbility();
                    Time.Start();
                }
                else if (!Me.HasModifier("modifier_pudge_rot") && v.Count(x => x.Distance2D(Me) <= W.GetCastRange() + Me.HullRadius) > 0)
                {
                    W.ToggleAbility();
                    Time.Start();
                }
            }

            E = Toolset.ClosestToMouse(Me);
            if (E == null || !Me.IsAlive)
            {
                return;
            }
            Sheep = E.ClassId == ClassId.CDOTA_Unit_Hero_Tidehunter ? null : Me.FindItem("item_sheepstick");
            if (R.IsInAbilityPhase || R.IsChanneling || Me.IsChanneling())
            {
                return;
            }
            if (Active)
            {
                MinRangeHook = E.HullRadius + 27;
                CastRange    = Leans != null ? (Q.CastRange + 200 + E.HullRadius) : (Q.CastRange + E.HullRadius);
                EMoveSpeed   = E.HasModifier("modifier_spirit_breaker_charge_of_darkness") ? 550 + ((int)E.Spellbook.Spell1.Level * 50) : E.MovementSpeed;

                Vector2 vector = new Vector2((float)Math.Cos(E.RotationRad) * EMoveSpeed, (float)Math.Sin(E.RotationRad) * EMoveSpeed);
                Vector3 start  = new Vector3((float)((0.3 + (Game.Ping / 1000)) * Math.Cos(E.RotationRad) * EMoveSpeed + E.Position.X),
                                             (float)((0.3 + (Game.Ping / 1000)) * Math.Sin(E.RotationRad) * EMoveSpeed + E.NetworkPosition.Y), E.NetworkPosition.Z);
                Vector3 specialPosition = new Vector3((float)(MinRangeHook * Math.Cos(E.RotationRad) + E.NetworkPosition.X),
                                                      (float)(MinRangeHook * Math.Sin(E.RotationRad) + E.NetworkPosition.Y),
                                                      E.NetworkPosition.Z);
                HookPosition = Interception(start, vector, Me.Position, 1600);
                if (
                    Atos != null && Atos.CanBeCasted() && Me.CanCast() && !E.IsMagicImmune() && !E.HasModifier("modifier_spirit_breaker_charge_of_darkness") &&
                    Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Atos.Name) && Me.Distance2D(E) <= 1500 && Utils.SleepCheck("a")
                    )
                {
                    Atos.UseAbility(E);
                    Utils.Sleep(250, "a");
                }
                else if (Q.CanBeCasted() && Menu.Item("Skills").GetValue <AbilityToggler>().IsEnabled(Q.Name))
                {
                    if (E.NetworkActivity == NetworkActivity.Move || E.HasModifier("modifier_spirit_breaker_charge_of_darkness"))
                    {
                        for (double i = 0.03; i <= 0.135; i += 0.03)
                        {
                            Vector3 estimated = new Vector3((float)(i * Math.Cos(E.RotationRad) * EMoveSpeed + HookPosition.X),
                                                            (float)(i * Math.Sin(E.RotationRad) * EMoveSpeed + HookPosition.Y), E.NetworkPosition.Z);
                            if (GetTimeToTurn(estimated) <= i)
                            {
                                HookPosition = estimated;
                                TimeTurn     = i;
                                break;
                            }
                        }
                        CastPos = (HookPosition - Me.Position) * ((Q.GetCastRange() + Me.HullRadius) / HookPosition.Distance2D(Me.Position)) + Me.Position;
                        if (Me.Position.Distance2D(HookPosition) < CastRange)
                        {
                            Q.UseAbility(CastPos); Time.Interval = 150 + TimeTurn * 1000;
                            Time.Start();
                        }
                    }
                    else
                    {
                        CastPos = (specialPosition - Me.Position) * ((Q.GetCastRange() + Me.HullRadius) / specialPosition.Distance2D(Me.Position)) + Me.Position;
                        if (Me.Position.Distance2D(E.NetworkPosition) < CastRange)
                        {
                            Q.UseAbility(CastPos);
                            Time.Start();
                        }
                    }
                }
                else
                {
                    if (R.IsInAbilityPhase || R.IsChanneling)
                    {
                        return;
                    }
                    uint countElse = 0;
                    countElse += 1;
                    if (Vail != null && Vail.CanBeCasted() && Me.Distance2D(E) <= 1100 && Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Vail.Name) && Utils.SleepCheck("vail"))
                    {
                        Vail.UseAbility(E.Position);
                        Utils.Sleep(130, "vail");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Orchid != null && Orchid.CanBeCasted() && Me.Distance2D(E) <= 900 && Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Orchid.Name) && Utils.SleepCheck("orchid"))
                    {
                        Orchid.UseAbility(E);
                        Utils.Sleep(100, "orchid");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Shiva != null && Shiva.CanBeCasted() && Me.Distance2D(E) <= 600 && Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Shiva.Name) && !E.IsMagicImmune() && Utils.SleepCheck("Shiva"))
                    {
                        Shiva.UseAbility();
                        Utils.Sleep(100, "Shiva");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Ethereal != null && Ethereal.CanBeCasted() && Me.Distance2D(E) <= 700 && Me.Distance2D(E) <= 400 && Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Ethereal.Name) && Utils.SleepCheck("ethereal"))
                    {
                        Ethereal.UseAbility(E);
                        Utils.Sleep(100, "ethereal");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Dagon != null && Dagon.CanBeCasted() && Me.Distance2D(E) <= Dagon.GetCastRange() && Utils.SleepCheck("dagon"))
                    {
                        Dagon.UseAbility(E);
                        Utils.Sleep(100, "dagon");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Urn != null && Urn.CanBeCasted() && Urn.CurrentCharges > 0 && Me.Distance2D(E) <= 400 && Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Urn.Name) && Utils.SleepCheck("urn"))
                    {
                        Urn.UseAbility(E);
                        Utils.Sleep(240, "urn");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Glimmer != null && Glimmer.CanBeCasted() && Me.Distance2D(E) <= 300 && Utils.SleepCheck("glimmer"))
                    {
                        Glimmer.UseAbility(Me);
                        Utils.Sleep(200, "glimmer");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Mail != null && Mail.CanBeCasted() && v.Count(x => x.Distance2D(Me) <= 650) >=
                        (Menu.Item("Heel").GetValue <Slider>().Value) &&
                        Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Mail.Name) &&
                        Utils.SleepCheck("mail"))
                    {
                        Mail.UseAbility();
                        Console.WriteLine(countElse.ToString());
                        Utils.Sleep(100, "mail");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Bkb != null && Bkb.CanBeCasted() && v.Count(x => x.Distance2D(Me) <= 650) >=
                        (Menu.Item("Heel").GetValue <Slider>().Value) &&
                        Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Bkb.Name) &&
                        Utils.SleepCheck("bkb"))
                    {
                        Bkb.UseAbility();
                        Utils.Sleep(100, "bkb");
                    }

                    else
                    {
                        countElse += 1;
                    }
                    if (Lotus != null && Lotus.CanBeCasted() && v.Count(x => x.Distance2D(Me) <= 650) >= 2 &&
                        Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Lotus.Name) &&
                        Utils.SleepCheck("lotus"))
                    {
                        Lotus.UseAbility(Me);
                        Utils.Sleep(100, "lotus");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (countElse == 11 && R != null && R.CanBeCasted() && Me.Distance2D(E) <= R.GetCastRange() + 150 && (!Urn.CanBeCasted() || Urn.CurrentCharges <= 0) && Menu.Item("Skills").GetValue <AbilityToggler>().IsEnabled(R.Name) &&
                        Utils.SleepCheck("R")
                        )
                    {
                        R.UseAbility(E);
                        Utils.Sleep(150, "R");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Abyssal != null && !R.CanBeCasted() && Abyssal.CanBeCasted() && !E.IsStunned() && !E.IsHexed() &&
                        Me.Distance2D(E) <= 300 && Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Abyssal.Name) && Utils.SleepCheck("abyssal"))
                    {
                        Abyssal.UseAbility(E);
                        Utils.Sleep(200, "abyssal");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (Sheep != null && !R.CanBeCasted() && Sheep.CanBeCasted() && !E.IsStunned() && !E.IsHexed() &&
                        Me.Distance2D(E) <= 900 && Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Sheep.Name) && Utils.SleepCheck("sheep"))
                    {
                        Sheep.UseAbility(E);
                        Utils.Sleep(200, "sheep");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (countElse == 14 && Me.Distance2D(E) <= 300 && Mail != null &&
                        Mail.CanBeCasted() && (E.NetworkActivity == NetworkActivity.Attack || E.Spellbook.Spells.All(x => x.IsInAbilityPhase)) &&
                        Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Mail.Name) &&
                        Utils.SleepCheck("mail"))
                    {
                        Mail.UseAbility();
                        Utils.Sleep(100, "mail");
                    }
                    else
                    {
                        countElse += 1;
                    }
                    if (countElse == 15 && Lotus != null && Lotus.CanBeCasted() && Me.Distance2D(E) <= 600 &&
                        Menu.Item("Items").GetValue <AbilityToggler>().IsEnabled(Lotus.Name) &&
                        Utils.SleepCheck("lotus"))
                    {
                        Lotus.UseAbility(Me);
                        Utils.Sleep(100, "lotus");
                    }
                    if ((R == null || !R.CanBeCasted() || !Q.CanBeCasted() && Me.Distance2D(E) >= R.GetCastRange() + Me.HullRadius && !E.HasModifier("pudge_meat_hook")) && !E.IsAttackImmune())
                    {
                        if (Menu.Item("orbwalk").GetValue <bool>() && Me.Distance2D(E) <= 1900)
                        {
                            Orbwalking.Orbwalk(E, 0, 1600, true, true);
                        }
                    }
                }
            }
        }