private void SearchInRangeTargets()
    {
        Collider[] colliders    = Physics.OverlapSphere(transform.position, AttackRange);
        Transform  attackTarget = null;
        float      minDistance  = float.MaxValue;

        foreach (Collider col in colliders)
        {
            if (col.gameObject.GetComponent <Unit> () == null)
            {
                continue;
            }
            Unit foundUnit = col.gameObject.GetComponent <Unit> ();

            if (foundUnit.getOwner() == owner)
            {
                continue;
            }
            float distance = Vector3.Distance(transform.position, foundUnit.transform.position);
            if (distance < minDistance)
            {
                attackTarget = foundUnit.transform;
                minDistance  = distance;
            }
        }
        if (attackTarget == null)
        {
            return;
        }
        //Debug.Log ("Attack: " + attackTarget.name);
        //Debug.Log ("-Distance: " + minDistance);
        target = new WalkType(attackTarget);
    }
        public void PlayEffect(WalkType walkType, MatType groundMatType, Transform parent, Vector3 position,
                               Vector3 pos, bool flip = false)
        {
            Vector3 playAnimNameLocation;

            if (flip == false)
            {
                playAnimNameLocation = position + pos;
            }
            else
            {
                playAnimNameLocation = position - pos;
            }

            string animEffectId = GetEffectId(walkType, groundMatType);

            Debug.Assert(string.IsNullOrWhiteSpace(animEffectId) == false,
                         "animEffectId == " + animEffectId == null ? "null" : animEffectId);

//            if (isGround == false)
//            {
//                Debug.Log("stop play animor");
//            }
//            else
//            {
//
//            }

            AnimManager.Instance.PlayAnimEffect(animEffectId, playAnimNameLocation, 0, flip,
                                                Vector3.zero, parent, 0);
        }
 public void setTarget(WalkType newTarget)
 {
     transform.parent.position = newTarget.getTargetPosition() + new Vector3(
         Random.Range(-3.0f, 3.0f),
         Random.Range(-3.0f, 3.0f),
         Random.Range(0.0f, 5.0f));
 }
        static int GetBestBridgeIn(WalkType walkType, List <PathfindNode> tmpIntermediate, PathfindNode previousPoint, PathfindNode endPoint)
        {
            int   bestBridge   = -1;
            float bestDistance = float.MaxValue;

            for (int i = 0; i < tmpIntermediate.Count; i++)
            {
                //float dist = (tmpIntermediate [i].Point - previousPoint.Point).EuclidiantMagnitude ();
                float dist   = (tmpIntermediate[i].Point.ToVector2() - previousPoint.Point.ToVector2()).magnitude;              //NawakTools.GetDistanceToLine(tmpIntermediate [i].Point.ToVector2(), previousPoint.Point.ToVector2(),endPoint.Point.ToVector2());//(tmpIntermediate [i].Point - previousPoint.Point).EuclidiantMagnitude ();
                float weight = 0.3f;
                //Debug.Log("befor: " + dist);
                dist += weight * (previousPoint.Point - tmpIntermediate [i].Point).Magnitude();
                //dist += weight*(endPoint.Point - tmpIntermediate [i].Point).Magnitude();
                //Debug.Log("after: " + dist);
                if (dist < bestDistance)
                {
                    bestBridge   = i;
                    bestDistance = dist;
                }
            }
            if (bestBridge == -1)
            {
                Debug.Break();
            }
            //Debug.Log("bestbridgr :" + tmpIntermediate[bestBridge] + " : " + previousPoint + " : " + endPoint);
            return(bestBridge);
        }
Beispiel #5
0
 public override bool HandleWalkAction(Creature creature, GameWorld world, WalkType type)
 {
     if (walkItems.ContainsKey(this.ItemID))
     {
         return(walkItems[ItemID](this, creature, world, type));
     }
     return(true);
 }
Beispiel #6
0
 public void Reset()
 {
     mWalkType                = WalkType.WALK;
     mTargetPos               = Vector3.zero;
     IsWalkingToOriginalPos   = false;
     IsWalkingToDropPos       = false;
     IsWalkingToCollectionPos = false;
 }
Beispiel #7
0
    void Awake()
    {
        audioSource = gameObject.AddComponent<AudioSource>();
        audioSource.playOnAwake = false;

        walkDirtCount = walkDirt.Count;
        walkMarbleCount = walkMarble.Count;
        walkEnergyCount = walkEnergy.Count;

        walkType = WalkType.Dirt;
    }
Beispiel #8
0
    //public MapCellData(XLua.LuaTable mo)
    //{
    //    this.x = mo.Get<string,int>("x");
    //    this.y = mo.Get<string, int>("y");
    //    this.h = mo.Get<string, int>("h");
    //    this.id = mo.Get<string, int>("id");
    //    this.res = mo.Get<string, string>("res");
    //    this.walkType = (WalkType)System.Enum.Parse(typeof(WalkType), mo.Get<string, string>("walkType"));
    //    this.eventType = (EventType)System.Enum.Parse(typeof(EventType), mo.Get<string, string>("eventType"));
    //    this.buildingType = (BuildingType)System.Enum.Parse(typeof(BuildingType), mo.Get<string, string>("buildingType"));
    //    this.buildingRes = mo.Get<string, string>("buildingRes");
    //}



    public MapCellData(Hex mo)
    {
        this.x            = mo.data.x;
        this.y            = mo.data.y;
        this.h            = mo.data.h;
        this.id           = mo.data.id;
        this.res          = mo.data.res;
        this.walkType     = mo.data.walkType;
        this.eventType    = mo.data.eventType;
        this.buildingType = mo.data.buildingType;
        this.buildingRes  = mo.data.buildingRes;
    }
        private string GetEffectId(WalkType walkType, MatType groundMatType)
        {
            string          key = walkType.ToString() + "_" + groundMatType.ToString();
            RoleInteraction roleInteraction;

            if (roleInteractionDic.TryGetValue(key, out roleInteraction))
            {
                Debug.Log("roleInteraction.EffectsKey为" + roleInteraction.hurtEffect);
                return(roleInteraction.hurtEffect);
            }
            return(null);
        }
Beispiel #10
0
    protected void SearchInRangeTargets()
    {
        Collider[]      colliders      = Physics.OverlapSphere(transform.position, AutoAttackRange);
        List <Collider> enemyBuildings = new List <Collider> ();
        Transform       attackTarget   = null;
        float           minDistance    = float.MaxValue;

        foreach (Collider col in colliders)
        {
            if (col.gameObject.GetComponent <Unit> () == null && col.gameObject.GetComponent <Building> () == null)
            {
                continue;
            }
            Unit foundUnit = col.gameObject.GetComponent <Unit> ();
            if (foundUnit == null)
            {
                if (col.gameObject.GetComponent <Building> ().getOwner() != owner)
                {
                    enemyBuildings.Add(col);
                }
                continue;
            }
            if (foundUnit.getOwner() == owner)
            {
                continue;
            }
            float distance = Vector3.Distance(transform.position, foundUnit.transform.position);
            if (distance < minDistance)
            {
                attackTarget = foundUnit.transform;
                minDistance  = distance;
            }
        }
        if (attackTarget == null)
        {
            foreach (Collider col in enemyBuildings)
            {
                Building build    = col.gameObject.GetComponent <Building>();
                float    distance = Vector3.Distance(transform.position, build.transform.position);
                if (distance < minDistance)
                {
                    attackTarget = build.transform;
                    minDistance  = distance;
                }
            }
        }
        if (attackTarget == null)
        {
            return;
        }
        target = new WalkType(attackTarget);
    }
Beispiel #11
0
    /// <summary>
    /// 跑步到某地
    /// </summary>
    /// <param name="target"></param>
    public void RunTo(Vector3 target)
    {
        target = InstanceHelper.ClampInWalkableRange(target);

        if (TargetActor != null)
        {
            // Hmmm ActorMachine的TryRunToAlong似乎有点问题,部分时候会卡住,暂时屏蔽
            m_WalkId = TargetActor.MoveCtrl.TryWalkToAlong(target);
        }

        mWalkType  = WalkType.RUN;
        mTargetPos = target;
    }
Beispiel #12
0
        private static void WalkCommon(Packet packet, IClient client, bool fromQueue, WalkType walkType)
        {
            Direction direction = (Direction)packet.GetChar();
            //TODO: SpeedTimestamp
            //SpeedTimestamp timestamp = new SpeedTimestamp(packet.GetThree());
            int timestamp = packet.GetThree();
            byte x = packet.GetChar();
            byte y = packet.GetChar();

            client.Character.Walk(direction, walkType, true);

            if (client.Character.X != x || client.Character.Y != y)
                client.Character.Refresh();
        }
        /// <summary>
        /// Constructs the npc manager.
        /// </summary>
        public NpcManager()
        {
            // Load definitions.
            this.definitions = NpcDefinition.Load();

            // Load spawns.
            try
            {
                DataRow[] rows = null;

                // Get all spawns.
                using (SqlDatabaseClient client = GameServer.Database.GetClient())
                {
                    DataTable table = client.ReadDataTable("SELECT * FROM npc_spawns;");

                    if (table != null)
                    {
                        rows = table.Select();
                    }
                }

                // If there is any spawns in the database, spawn them in game.
                if (rows != null)
                {
                    foreach (DataRow row in rows)
                    {
                        //DataRow row = rows[0];
                        short    id             = (short)row[1];
                        Location originalCoords = Location.Create((short)row[2], (short)row[3], (byte)row[4]);
                        WalkType walkType       = (WalkType)row[5];
                        Location minRange       = Location.Create((short)row[6], (short)row[7], (byte)row[8]);
                        Location maxRange       = Location.Create((short)row[9], (short)row[10], (byte)row[11]);

                        string[] messages = null;
                        if (row[12] is string)
                        {
                            messages = ((string)row[12]).Split(';');
                        }

                        Npc npc = new Npc(id, originalCoords, minRange, maxRange, walkType, definitions[id], messages);
                        RegisterNpc(npc);
                    }
                    //Program.Logger.WriteInfo("Loaded " + this.definitions.Count + " npc definitions, and " + this.npcSpawns.Count + " spawn(s).");
                }
            }
            catch (Exception ex)
            {
                Program.Logger.WriteException(ex);
            }
        }
Beispiel #14
0
 public static void InitMovTab(WalkType type)
 {
     moveTable.Clear();
     foreach (var p in Grid2D <int> .ortho)
     {
         moveTable.Add(p);
     }
     if (type == WalkType.Direction8)
     {
         foreach (var p in Grid2DInt.diago)
         {
             moveTable.Add(p);
         }
     }
 }
        private bool HasLinkBetween(int startGroup, int endGroup, WalkType walkType, ref List <int> linkedGroups)
        {
            bool HasNewGroups = false;

            for (int bri = instance.Bridges.Count - 1; bri >= 0; bri--)
            {
                PathfindNode bridge = instance.Bridges [bri];
                PathfindNodeGroupParameter groupParameter = bridge.GetParameter(walkType);
                bool containsPreviousGroup = linkedGroups.Contains(groupParameter.Group);
                for (int i = 0; i < groupParameter.GroupBridge.Count; i++)
                {
                    int bridgeGroup = groupParameter.GroupBridge [i];
                    if (linkedGroups.Contains(bridgeGroup))
                    {
                        containsPreviousGroup = true;
                    }
                }

                if (containsPreviousGroup)
                {
                    if (linkedGroups.Contains(groupParameter.Group) == false)
                    {
                        HasNewGroups = true;
                        linkedGroups.Add(groupParameter.Group);
                    }
                    for (int i = 0; i < groupParameter.GroupBridge.Count; i++)
                    {
                        int bridgeGroup = groupParameter.GroupBridge [i];
                        if (linkedGroups.Contains(bridgeGroup) == false)
                        {
                            HasNewGroups = true;
                            linkedGroups.Add(bridgeGroup);
                        }
                    }
                }
            }
            if (HasNewGroups)
            {
                return(HasLinkBetween(startGroup, endGroup, walkType, ref linkedGroups));
            }
            else
            {
                return(linkedGroups.Contains(endGroup));
            }
            return(false);
        }
//		private void PrecalcultateBridges()
//		{
//			for(int i = 0;i < Bridges.Count;i++)
//			{
//				foreach(WalkType walkType in Enum.GetValues(typeof(WalkType)).Cast<WalkType>().ToList())
//				{
//					for(int j = i;j < Bridges.Count;j++)
//					{
//						if(Bridges[i].GetParameter(walkType).GroupBridge.Count > 0 && Bridges[j].GetParameter(walkType).GroupBridge.Count > 0 )
//						{
//							AStartPathFinding(Bridges[i].Point,Bridges[j].Point);
//						}
//					}
//				}
//			}
//		}

        public bool HasBridgeBetween(PathfindNode startPoint, PathfindNode endPoint, WalkType walkType)
        {
//			if(m_linkedGroup == null)
//				m_linkedGroup = new Dictionary<int, List<int>>();
//
//			if(m_linkedGroup.ContainsKey(startPoint.GetParameter(walkType).Group) )
//				return m_linkedGroup[startPoint.GetParameter(walkType).Group].Contains(endPoint.GetParameter(walkType).Group);

            if (m_linkedGroupInfo == null)
            {
                m_linkedGroupInfo = new Dictionary <KeyValuePair <int, int>, bool>();
            }

            KeyValuePair <int, int> pair = new KeyValuePair <int, int>(startPoint.GetParameter(walkType).Group, endPoint.GetParameter(walkType).Group);

            if (m_linkedGroupInfo.ContainsKey(pair))
            {
                //Debug.Log("pair in dico");
                return(m_linkedGroupInfo[pair]);
            }

            List <int>          walkedGroup   = new List <int>();
            List <PathfindNode> intermediates = new List <PathfindNode>();

            intermediates.Add(startPoint);
            List <int> linkedGroups = new List <int>();

            linkedGroups.Add(startPoint.GetParameter(walkType).Group);
            bool hasLink = HasLinkBetween(startPoint.GetParameter(walkType).Group, endPoint.GetParameter(walkType).Group, walkType, ref linkedGroups);

//			if(m_linkedGroup.ContainsKey(startPoint.GetParameter(walkType).Group) == false)
//				m_linkedGroup.Add(startPoint.GetParameter(walkType).Group,linkedGroups);
//			else
//				m_linkedGroup[startPoint.GetParameter(walkType).Group] = linkedGroups;
            if (m_linkedGroupInfo.ContainsKey(pair) == false)
            {
                m_linkedGroupInfo.Add(pair, hasLink);
            }
            else
            {
                m_linkedGroupInfo[pair] = hasLink;
            }
            return(hasLink);
//			return GetIntermediatesPoint (startPoint.GetParameter(walkType).Group,
//			                              endPoint.GetParameter(walkType).Group, walkType,ref walkedGroup,ref intermediates,endPoint);
        }
Beispiel #17
0
        /// <summary>
        /// Constructs a new npc.
        /// </summary>
        /// <param name="indexId">The npc's client index id.</param>
        /// <param name="cacheIndexId">The npc's cache index id.</param>
        /// <param name="originalCoords">Original location at which the npc will always spawn at.</param>
        /// <param name="minRange">The min range at which the npc can walk to.</param>
        /// <param name="maxRange">The max range at which the npc can walk to.</param>
        /// <param name="type">The type of walking the npc does.</param>
        public Npc(int cacheIndexId, Location originalCoords, Location minRange,
                   Location maxRange, WalkType type, NpcDefinition definition, string[] messages) : base(originalCoords)
        {
            this.Sprite           = -1;
            this.CacheIndex       = cacheIndexId;
            this.OriginalLocation = originalCoords;
            this.MinimumRange     = minRange;
            this.MaximumRange     = maxRange;
            this.WalkType         = type;

            this.Definition    = definition;
            this.Name          = this.Definition.Name;
            this.HitPoints     = this.Definition.HitPoints;
            this.speakMessages = messages;

            this.UpdateFlags  = new UpdateFlags();
            this.WalkingQueue = new WalkingQueue(this);
        }
Beispiel #18
0
//		public void BuildParameter()
//		{
//			CreateParameter();
//			if(Walkable == false)
//			{
//				int t=0;
//				t++;
//			}
//			GetParameter((int)WalkType.Walk).Enable = Walkable;
//			GetParameter((int)WalkType.Fly).Enable = Flyable;
//
//			GetParameter((int)WalkType.Walk).Group = Group;
//			GetParameter((int)WalkType.Fly).Group = 0;
//		}
        public PathfindNodeGroupParameter GetParameter(WalkType type)
        {
            if (listParameters == null)
            {
                CreateParameter();
            }

            foreach (PathfindNodeGroupParameter param in listParameters)
            {
                if (param.WalkType == type)
                {
                    return(param);
                }
            }
            PathfindNodeGroupParameter newparam = new PathfindNodeGroupParameter(type);

            listParameters.Add(newparam);

            return(newparam);
        }
Beispiel #19
0
    // Update is called once per frame
    void Update()
    {
        if (Health <= 0)
        {
            Die();
        }
        updateUnit();

        if (target != null && target.WType == WType.Collect)
        {
            if (collided == null)
            {
                if (agent.isOnNavMesh)
                {
                    agent.isStopped = false;
                }
                if (Vector3.Distance(transform.position, target.getTargetPosition()) < 1.4f ||
                    (Vector3.Distance(transform.position, target.getTargetPosition()) < 14f &&
                     agent.velocity.magnitude < 3f))
                {
                    target = null;
                    Transform selectedResource = null;
                    float     minDist          = ResourceRange;
                    foreach (var r in gm.Resources)
                    {
                        float tempdist = 0;
                        if ((tempdist = Vector3.Distance(r.position, transform.position)) < minDist)
                        {
                            minDist          = tempdist;
                            selectedResource = r;
                        }
                    }
                    if (selectedResource != null)
                    {
                        target = new WalkType(selectedResource.position, WType.Collect);
                    }
                }
            }
        }
        TargetType = target == null ? "" : target.WType.ToString();
    }
Beispiel #20
0
        public bool ContainsGroupOf(PathfindNode node, WalkType walks)
        {
//			if(node.Point == new Point(45,23))
//			{
//				int dsd=0;
//				dsd +=1;
//			}
            if (ContainsGroup(node.GetParameter(WalkType).Group))
            {
                return(true);
            }
            foreach (int group in node.GetParameter(WalkType).GroupBridge)
            {
                if (ContainsGroup(group))
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #21
0
 void OnTriggerStay(Collider collider)
 {
     if (target != null && target.WType == WType.Collect && collider.tag.Equals("Resource"))
     {
         //Sammel Resourcen ein!
         collided = collider.gameObject;
         collectRessources(collided);
         //agent.SetDestination(transform.position);
     }
     else if (target != null && target.WType == WType.ReturnResources && carry > 0 && collider.tag.Equals("MainBuilding") && collider.GetComponent <MainBuilding>().getOwner() == owner)
     {
         //Füge die Resourcen dem Lager hinzu
         User user = GameMaster.Instance.Players[owner];
         user.IncreaseResources(carry);
         carry = 0;
         if (saveTarget != null)
         {
             target = saveTarget;
         }
     }
 }
Beispiel #22
0
    /// <summary>
    /// 走路到某地-
    /// </summary>
    /// <param name="target"></param>
    public void WalkTo(Vector3 target)
    {
        if (TargetActor != null)
        {
            target.y = RoleHelp.GetHeightInScene(TargetActor.ActorId, target.x, target.z);
            target   = InstanceHelper.ClampInWalkableRange(target, 10);

            if (TargetActor.IsAttacking() == true)
            {
                Skill cur_skill = TargetActor.GetCurSkill();
                if (cur_skill != null)
                {
                    cur_skill.End();
                }
            }
            m_WalkId = TargetActor.MoveCtrl.TryWalkToAlong(target);
        }

        mWalkType  = WalkType.WALK;
        mTargetPos = target;
    }
        static List <PathfindNode> GetAllBridges(int from, int to, WalkType walkType)
        {
            List <PathfindNode> tmpIntermediate = new List <PathfindNode>();

            for (int bri = instance.Bridges.Count - 1; bri >= 0; bri--)
            {
                PathfindNode bridge = instance.Bridges [bri];
                PathfindNodeGroupParameter groupParameter = bridge.GetParameter(walkType);
                if (groupParameter.Group == from || groupParameter.Group == to)
                {
                    for (int i = 0; i < groupParameter.GroupBridge.Count; i++)
                    {
                        int bridgeGroup = groupParameter.GroupBridge [i];
                        if (bridgeGroup == to || bridgeGroup == from)
                        {
                            tmpIntermediate.Add(bridge);
                        }
                    }
                }
            }
            return(tmpIntermediate);
        }
        static bool BelongSameGroup(PathfindNode startPoint, PathfindNode endPoint, WalkType walktype)
        {
            List <int> StartsGroups = new List <int>();

            foreach (int b in startPoint.GetParameter(walktype).GroupBridge)
            {
                StartsGroups.Add(b);
            }
            StartsGroups.Add(startPoint.GetParameter(walktype).Group);
            if (StartsGroups.Contains(endPoint.GetParameter(walktype).Group))
            {
                return(true);
            }
            foreach (int b in endPoint.GetParameter(walktype).GroupBridge)
            {
                if (StartsGroups.Contains(b))
                {
                    return(true);
                }
            }
            return(false);
            //return (startPoint.GetParameter(walkType).Group != endPoint.GetParameter (walkType).Group);
        }
Beispiel #25
0
 public override bool HandleWalkAction(Creature creature, GameWorld world, WalkType type)
 {
     if (walkItems.ContainsKey(this.ItemID)) {
         return walkItems[ItemID](this, creature, world, type);
     }
     return true;
 }
Beispiel #26
0
 public void setTarget(WalkType newTarget)
 {
     agent.isStopped = false;
     this.target     = newTarget;
 }
Beispiel #27
0
 public Locomotion() {
     this.mannerField = WalkType.WALK;
 }
 public void Start()
 {
     buildingUi = GetComponentInChildren <BuildingUi>();
     buildingUi.gameObject.SetActive(false);
     target = null;
 }
 public void setTarget(WalkType newTarget)
 {
     target = newTarget;
 }
        private static IEnumerator AStartPathFinding(PathfindNode startPoint, PathfindNode endPoint, PathComplete Callback, Dictionary <Point, PathfindNode> walkableArea, WalkType walkType, int loopMaxCount = int.MaxValue)
        {
            if (startPoint.Point == endPoint.Point)
            {
                Callback.Invoke(null);
            }
            int startGroup = startPoint.GetParameter(walkType).Group;

            if (PathFindingManager.PrecalculatedPaths != null)
            {
//                foreach(PointCouple couple in PathFindingManager.PrecalculatedPaths.Keys)
//                {
//                    //Debug.Log(couple);
//                    if(couple.StartPoint == startPoint.Point && couple.EndPoint == endPoint.Point)
//                    {
//                      //  Debug.Log("FIND COUPLE");
//                    }
//                }
                if (PathFindingManager.PrecalculatedPaths.ContainsKey(new PointCouple(startPoint.Point, endPoint.Point)))
                {
                    //instance.Processing = false;
                    Callback.Invoke(PathFindingManager.PrecalculatedPaths[new PointCouple(startPoint.Point, endPoint.Point)].Clone());
                    yield break;
                }
            }

            Dictionary <Point, PathfindNode> reachablePoints = walkableArea;          // s_instance.CompleteArea;

            if (reachablePoints.ContainsKey(endPoint.Point) == false)
            {
                //Debug.Log("Node not reachable: "+endPoint.Point);
                //instance.Processing = false;
                Callback.Invoke(null);
                yield break;
            }
//			if (BelongSameGroup (startPoint,endPoint,walkType) == false) {
//
//				int endGroup = endPoint.GetParameter (walkType).Group;
//				List<int> walkedGroup = new List<int>();
//				List<PathfindNode> intermediates = new List<PathfindNode>();
//				intermediates.Insert(0,startPoint);
//				bool succes = GetIntermediatesPoint (startGroup, endGroup, walkType,ref walkedGroup,ref intermediates,endPoint);
//				if(succes == false)
//				{
//					//instance.Processing = false;
//					Callback.Invoke(null);
//					yield break;
//				}
//				intermediates.Add(endPoint);
//				Enemy PathOwner = Callback.Target as Enemy;
//				PathOwner.ClearStepedPath();
//				for(int i =0;i<intermediates.Count-1;i++)
//				{
//					yield return instance.StartCoroutine (AStartPathFinding (intermediates [i], intermediates [i+1], PathOwner.BuildPathFromStepCallback, walkableArea, walkType, loopMaxCount));
//				}
//
//				//instance.Processing = false;
//				Callback.Invoke(PathOwner.GetStepedPath());
//				yield break;
//			}
            List <AStarNode> openSet = new List <AStarNode>();
            Dictionary <Point, AStarNode> openSetDico = new Dictionary <Point, AStarNode>();

            openSet.Add(new AStarNode(startPoint));
            openSetDico.Add(startPoint.Point, openSet[openSet.Count - 1]);
            Dictionary <Point, AStarNode> closedSet = new Dictionary <Point, AStarNode>();

            float fscore;                                                    // = (endPoint-startPoint).MagnitudeZero();

            fscore = Point.MagnitudeZero(endPoint.Point - startPoint.Point); //+(1 -Vector2.Dot(toNeighbor,toEnd))*20;

            int loopLimit = 0;

            while (openSet.Count > 0 && loopMaxCount > 0)
            {
                //Debug.Log(openSet.Count);
                loopMaxCount--;
                loopLimit++;
                openSet.Sort();
                AStarNode current = openSet[0];
                if (current.Position == endPoint)
                {
                    Path path = new Path(endPoint);
                    while (current.Parent != null)
                    {
                        path.steps.Add(current.Position);
                        current = current.Parent;
                    }
                    path.steps.Reverse();



                    if (PathFindingManager.PrecalculatedPaths == null)
                    {
                        PathFindingManager.PrecalculatedPaths = new Dictionary <PointCouple, Path>();
                    }
                    PointCouple couple = new PointCouple(startPoint.Point, endPoint.Point);
                    if (PathFindingManager.PrecalculatedPaths.ContainsKey(couple))
                    {
                        Debug.Log("Try add existing couple: " + couple);
                    }
                    else
                    {
                        PathFindingManager.PrecalculatedPaths.Add(couple, path);
                    }

                    //instance.Processing = false;
                    Callback.Invoke(path.Clone());
                    yield break;
                }
                openSetDico.Remove(openSet[0].Position.Point);
                openSet.RemoveAt(0);
                closedSet.Add(current.Position.Point, current);
                if (loopLimit > 10)
                {
                    yield return(new WaitForEndOfFrame());

                    loopLimit = 0;
                }
                for (int i = 0; i < Neighbourhood.Length; i++)
                {
                    PathFindNeighbourg neighbourPath        = Neighbourhood [i];
                    PathfindNode       neighbour            = new PathfindNode(neighbourPath.offset);
                    PathfindNode       neigbourRealPosition = neighbour + current.Position;
                    if (reachablePoints.ContainsKey(neigbourRealPosition.Point) == false)
                    {
                        continue;
                    }
                    AStarNode AstarNeighbor = new AStarNode(neigbourRealPosition);
                    AstarNeighbor.Position = neigbourRealPosition;
                    //current.Position;
                    AstarNeighbor.Parent = current;
                    if (closedSet.ContainsKey(AstarNeighbor.Position.Point))
                    {
                        continue;
                    }
                    bool containsStartGroup = instance.CompleteNodeArea.GetNodeAt(neigbourRealPosition.Point).GetParameter(walkType).ContainsGroupOf(endPoint, walkType);
                    if (containsStartGroup == false)
                    {
                        continue;
                    }
                    float     tentativeGscore = current.gscore + neighbourPath.cost;
                    AStarNode InSetNeighbor   = null;
                    //GetNodeInList(AstarNeighbor,openSet);
                    if (openSetDico.ContainsKey(AstarNeighbor.Position.Point))
                    {
                        InSetNeighbor = openSetDico [AstarNeighbor.Position.Point];
                    }
                    if (InSetNeighbor == null || tentativeGscore < InSetNeighbor.gscore)
                    {
                        bool needAddToSet = false;
                        if (InSetNeighbor == null)
                        {
                            InSetNeighbor = new AStarNode(neigbourRealPosition);
                            needAddToSet  = true;
                        }
                        InSetNeighbor.Parent = current;
                        InSetNeighbor.gscore = tentativeGscore;
                        InSetNeighbor.fscore = InSetNeighbor.gscore + heuristique(AstarNeighbor, endPoint.Point, current.Position.Point);
                        if (needAddToSet)
                        {
                            AstarNeighbor.fscore = InSetNeighbor.fscore;
                            AstarNeighbor.gscore = InSetNeighbor.gscore;
                            openSet.Add(AstarNeighbor);
                            openSetDico.Add(AstarNeighbor.Position.Point, openSet [openSet.Count - 1]);
                        }
                    }
                }
            }

            //instance.Processing = false;
            Callback.Invoke(null);
            //return null;
        }
Beispiel #31
0
 public PathfindNodeGroupParameter(WalkType type) : this()
 {
     WalkType = type;
 }
Beispiel #32
0
        public PathfindNodeGroupParameter GetParameter(int m_curentTab)
        {
            WalkType type = (WalkType)m_curentTab;

            return(GetParameter(type));
        }
        //return succes
        private static bool GetIntermediatesPoint(int startGroup, int endGroup, WalkType walkType, ref List <int> WalkedGroup, ref List <PathfindNode> intermediate, PathfindNode targetPoint)
        {
            List <PathfindNode> tmpIntermediate  = new List <PathfindNode>();
            List <PathfindNode> stepIntermediate = new List <PathfindNode>();

            for (int bri = instance.Bridges.Count - 1; bri >= 0; bri--)
            {
                PathfindNode bridge = instance.Bridges [bri];
                PathfindNodeGroupParameter groupParameter = bridge.GetParameter(walkType);
                if (groupParameter.Group == startGroup || groupParameter.Group == endGroup)
                {
                    for (int i = 0; i < groupParameter.GroupBridge.Count; i++)
                    {
                        int bridgeGroup = groupParameter.GroupBridge [i];
                        if (bridgeGroup == endGroup || bridgeGroup == startGroup)
                        {
                            groupParameter.GroupBridge [i] = endGroup;
                            groupParameter.Group           = startGroup;
                            tmpIntermediate.Add(bridge);
                        }
                    }
                }
            }
            if (tmpIntermediate.Count > 0)
            {
                int bestBridge = GetBestBridgeIn(walkType, tmpIntermediate, intermediate [intermediate.Count - 1], targetPoint);
                intermediate.Add(tmpIntermediate [bestBridge]);
                PathfindNodeGroupParameter NextPointIntermediate = tmpIntermediate [bestBridge].GetParameter(walkType);
                return(true);
            }
            else
            {
                WalkedGroup.Add(startGroup);
                for (int bri = instance.Bridges.Count - 1; bri >= 0; bri--)
                {
                    PathfindNode bridge = instance.Bridges [bri];
                    PathfindNodeGroupParameter groupParameter = bridge.GetParameter(walkType);
                    List <int> bridgeGroups = new List <int>(groupParameter.GroupBridge);
                    bridgeGroups.Add(groupParameter.Group);
                    if (bridgeGroups.Contains(startGroup))
                    {
                        for (int i = 0; i < bridgeGroups.Count; i++)
                        {
                            if (WalkedGroup.Contains(bridgeGroups[i]) == false)
                            {
                                int newGroupIndex = bridgeGroups[i];
                                List <PathfindNode> localBridges = GetAllBridges(bridgeGroups[i], startGroup, walkType);
                                int          bestBridgeIndex     = GetBestBridgeIn(walkType, localBridges, intermediate [intermediate.Count - 1], targetPoint);
                                PathfindNode bestBridge          = null;
                                if (bestBridgeIndex >= 0)
                                {
                                    bestBridge = localBridges[bestBridgeIndex];
                                }
                                else
                                {
                                    Debug.Log("can't find bestbrige");
                                    Debug.Break();
                                }
                                intermediate.Add(bestBridge);
                                if (GetIntermediatesPoint(bridgeGroups[i], endGroup, walkType, ref WalkedGroup, ref intermediate, targetPoint))
                                {
                                    return(true);
                                }
                                else
                                {
                                    intermediate.Remove(bestBridge);
                                }
                            }
                        }
                    }
                }
                return(false);
            }
        }
Beispiel #34
0
        /**
         * @param walkType the walkType to set
         */

        public void setWalkType(WalkType walkType)
        {
            this.walkType = walkType;
        }
Beispiel #35
0
 /**
 * @param walkType the walkType to set
 */
 public void setWalkType(WalkType walkType)
 {
     this.walkType = walkType;
 }