protected void Awake() { _botRenderer = BotPart.GetComponent <SpriteRenderer>(); if (_botRenderer == null) { Debug.LogWarning("There's no renderer attached on bot part"); gameObject.SetActive(false); return; } _myAgent = GetComponent <AStarAgent>(); if (_myAgent == null) { Debug.LogWarning("There's no agent attached"); gameObject.SetActive(false); return; } _myAgent.MyGrid = GameController.Instance.MainGrid; _myAgent.TargetObject = GameController.Instance.IslandTransfrom; _trailRenderer = transform.GetComponentInChildren <TrailRenderer>(); if (_trailRenderer == null) { Debug.LogWarning("There's no trail renderer attached"); gameObject.SetActive(false); return; } _trailRenderer.sortingLayerID = _botRenderer.sortingLayerID; _trailRenderer.sortingOrder = _botRenderer.sortingOrder - 1; }
// 큐에 요청받은 내용을 구조체를 통하여 입력 public void RequestPathfinding(AStarAgent agent, Vector3 start, Vector3 end) { ARequestHandler handler = new ARequestHandler(agent, start, end); m_requestQueue.Enqueue(handler); NextProcess(); }
public void RefreshAllPath() { #if USING_FLOW_FIELD if (_flowManager != null) { _flowManager.UpdateFlowFields(); } #endif int taskCount = _tasks.Count; int pathMcount = taskCount + 1; for (int k = 0; k < pathMcount; k++) { int aCount = _pathManagers[k]._agentIdx.Count; for (int j = 0; j < aCount; j++) { if (_pathManagers[k]._agentIdx[j].AgentType == EAgentType.astar) { AStarAgent aa = _pathManagers[k]._agentIdx[j].agent as AStarAgent; if (aa != null) { aa.ClearPath(); } } } _pathManagers[k].Reset(); _pathManagers[k].ClearPath(); } }
public static void Window(AGrid grid) { m_window = GetWindow(typeof(AStarTestEditor)); AStarMng.Instance.Init(); AStarMng.Instance.Grid = grid; GameObject obj = new GameObject(typeof(AStarAgent).ToString(), typeof(AStarAgent)); m_agent = obj.AddComponent <AStarAgent>(); }
public override void Awake() { base.Awake(); _renderer = GetComponent <SpriteRenderer>(); if (_renderer == null) { Debug.LogWarning("There's no renderer attached"); gameObject.SetActive(false); return; } _boxCollider = GetComponent <BoxCollider2D>(); if (_boxCollider == null) { Debug.LogWarning("There's no collider attached"); gameObject.SetActive(false); return; } _trailRenderer = transform.GetComponentInChildren <TrailRenderer>(); if (_trailRenderer == null) { Debug.LogWarning("There's no trail renderer attached"); gameObject.SetActive(false); return; } _trailRenderer.sortingLayerID = _renderer.sortingLayerID; _trailRenderer.sortingOrder = _renderer.sortingOrder - 1; _particleSystem = transform.GetComponentInChildren <ParticleSystem>(); if (_particleSystem == null) { Debug.LogWarning("There's no particle system attached"); gameObject.SetActive(false); return; } _particleSystem.GetComponent <Renderer>().sortingLayerID = _renderer.sortingLayerID; _particleSystem.GetComponent <Renderer>().sortingOrder = _renderer.sortingOrder + 1; _myAgent = GetComponent <AStarAgent>(); if (_myAgent == null) { Debug.LogWarning("There's no agent attached"); gameObject.SetActive(false); return; } _baseScale = gameObject.transform.localScale; _speed = ShipManoeuvrability; _captureTime = CaptureTime; GameLord.Instance.OnReloadStage += OnReloadStage; InitializeShip(); }
public void CreateAstarPath(AStarAgent agent, TSVector start, TSVector target, GridMap map, int curPosIdx) { if (agent._asm == null) { AStarMachine.AStarMachine asm = _pathPool.New(); GridAStarGoal goal = _goalPool.New(); goal.Ini(agent); GridAStarStorage storage = _storagePool.New(); storage.Ini(); asm.Ini(agent, goal, storage, map); agent._asm = asm; StartFindingPath(asm, start, target, false, curPosIdx); } }
public void SpawnShoppers(WorldGrid wGrid) { for (int i = 0; i < numShoppers; i++) { bool spawned = false; Vector3 position = Vector3.zero; while (!spawned) { position = wGrid.GetRandomCell().worldPosition; spawned = Physics.CheckSphere(position, wGrid.cellSize); } AStarAgent a = Instantiate(shopperPrefab, position, Quaternion.identity) as AStarAgent; a.grid = wGrid; a.debugColor = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), a.debugColor.a); } }
public static BTNode ConstructTree(SBTNode t, AStarAgent AI) { List <BTNode> children = new List <BTNode>(); BTNode res = BTNodeFactory.BuildNode(t.type); foreach (SBTNode child in t.children) { BTNode c = ConstructTree(child, AI); children.Add(c); } res.variables = t.variables; res.childrenNodes = children; res.AI = AI; return(res); }
//public void RemovePath(IPathAgent agent) //{ // if(agent!=null) // { // _pathPool.Store((AStarMachine.AStarMachine)agent.Asm); // agent.Asm = null; // } //} internal void ClearFinishedPath(AStarMachine.AStarMachine path) { if (path.Agent != null) { AStarAgent agent = path.Agent as AStarAgent; if (agent._asm == path) { agent._asm = null; } } if (path.Goal != null && !path.IsWorking && !path._inQueue) //avoid storing the same obj repeatly { _goalPool.Store((GridAStarGoal)path.Goal); _storagePool.Store((GridAStarStorage)path.Storage); _pathPool.Store(path); } }
public virtual BaseCharacter Init(int groupHandle, float agentDensity, Stat baseStat, BaseState idle, BaseState attack, BaseState move, BaseState death, BaseState chase = null) { m_animator = GetComponent <Animator>(); m_stateMethodDic.Add(ECharacterState.Idle, idle); m_stateMethodDic.Add(ECharacterState.Attack, attack); m_stateMethodDic.Add(ECharacterState.Move, move); m_stateMethodDic.Add(ECharacterState.Death, death); m_agroCollider = gameObject.AddComponent <CircleCollider2D>(); m_agroCollider.radius = 3; m_agroCollider.isTrigger = true; m_stat = new StatFunction(baseStat); m_agent = new FlockingAgent(this, groupHandle, agentDensity); CharacterMng.Instance.AddGroupMember(groupHandle, this); m_astarAgent = gameObject.AddComponent <AStarAgent>(); return(this); }
/// <summary> /// three step:first step,find fast path,maybe not a valid path navigating to target position /// </summary> /// <param name="agent"></param> /// <param name="start"></param> /// <param name="target"></param> /// <param name="mapId"></param> /// <param name="isTried">is tried to find quick path and finished </param> /// <returns></returns> public EPathReturnStatus FindQuickPath(AgentBase agent, int revs, TSVector start, TSVector target, GridMap map, bool isTried)//, List<TSVector> vecPath { //GridMap map = GridMapManager.instance.GetMap(mapId); if (map.GetGridNodeId(start) == map.GetGridNodeId(target)) { return(EPathReturnStatus.ok); } AStarAgent aAgent = ((AStarAgent)agent); AStarMachine.AStarMachine asm = isTried?null: aAgent._asm; bool bInqueue = asm != null && asm.IsWorking; if (asm == null) { asm = _pathPool.New(); GridAStarGoal goal = _goalPool.New(); goal.Ini(agent); GridAStarStorage storage = _storagePool.New(); storage.Ini(); asm.Ini(agent, goal, storage, map); } int curIdx = map.GetGridNodeId(aAgent._behaviour.position); StartFindingPath(asm, start, target, true, curIdx); if (asm.IsWorking) { int startIdx = map.GetGridNodeId(start); int tIdx = map.GetGridNodeId(target); IInt2 pos = map.GetGridPos(tIdx); bool isReachable = map.IsExistingNeighbourWalkable(pos.x, pos.y, startIdx, tIdx, curIdx); if (!isTried && isReachable) { ProcessFinishedPath(asm, EPathType.quickPath, false);//quick path is valid } if (!isReachable) { aAgent._behaviour.AddUnReachablePos(map, tIdx); } if (!isTried && isReachable)//target possible reachable { int sIdx = map.GetGridNodeId(aAgent._vecRunningPath[0]); asm.StartSearch(sIdx, tIdx, false, start, _pathId++, startIdx);// //if (!bInqueue) //{ // _pathQueue.Enqueue(asm);//find full path //} aAgent._asm = asm; } else//can't reach target { asm.IsWorking = false; // asm.Reset(); ClearFinishedPath(asm); if (!isTried) { return(EPathReturnStatus.fail); #if UNITY_EDITOR && !MULTI_THREAD if (PathFindingManager.DEBUG) { UnityEngine.Debug.LogWarning("can't reach target:" + pos.x + "," + pos.y); } #endif } else { return(EPathReturnStatus.fail); } } // asm._start= } else { if (isTried)//remove working asm { if (aAgent._asm != null) { aAgent._asm.IsWorking = false; ClearFinishedPath(aAgent._asm); } aAgent._asm = asm; } ProcessFinishedPath(asm, EPathType.quickPath);//quick path is valid } if (aAgent._vecRunningPath.Count > 0) { return(EPathReturnStatus.ok); } return(EPathReturnStatus.fail);//warning }
public void Loop() { if (!enabled || !gameObject.activeSelf) { return; } if (!unit.enabled) { unit.OnEnable(); unit.ChangeAgentType(unit._baseData.eAgentType == EAgentType.ingoreObstacle? EAgentType.ingoreObstacle : EAgentType.astar); unit.agent.TargetPos = unit._defaultTargetPos; } CalculateEnemies(); TestAgent agent = null; FP tagetDstSqr = FP.MaxValue; if (_targetId >= 0) { agent = _testPathFinding.GetAgent(_targetId); if (agent != null) { tagetDstSqr = (agent.unit.position - unit.position).sqrMagnitude; } } for (int i = 0; i < _listEnemyAgents.Count; i++) { FP trueRange = attackRange + _listEnemyAgents[i].colliderRadius; FP dstSqr = (_listEnemyAgents[i].position - unit.position).sqrMagnitude; if (dstSqr < trueRange * trueRange) //in attackage range { if (unit.AgentType != EAgentType.none) { unit.SetNewTargetPos(_listEnemyAgents[i].position);////////////////////////// unit.stopMoving = true; unit._nextCheckActionTime = 0; unit._frameOffset = 20; _targetId = _listEnemyAgents[i].baseData.id; } break; } if (_targetId >= 0 && dstSqr >= tagetDstSqr - GridMap.GetNodeSize() * GridMap.GetNodeSize() && _targetId != unit.Id) { if (agent != null && unit.CanSetTargetPos(agent.unit.position)) { break; } } if (unit.SetNewTargetPos(_listEnemyAgents[i].position)) { int idx1 = unit.map.GetGridNodeId(unit.NewTargetPos); int idx2 = unit.map.GetGridNodeId(unit.targetPos); if (idx1 != idx2) { unit.stopMoving = false; } _targetId = _listEnemyAgents[i].baseData.id; break; } } if (_listEnemyAgents.Count == 0 || _targetId == 0) { TSVector targetPos = CustomMath.Vector3ToTsvec(_testPathFinding.destObj[unit.playerId].transform.position); // unit.ChangeAgentType(EAgentType.flowFiled); if ((targetPos - unit.position).sqrMagnitude > GridMap._checkDeltaDstSqr) { unit.stopMoving = false; } if (unit.NewTargetPos == TSVector.MinValue || unit.NewTargetPos == TSVector.MaxValue || _targetId == 0) // || (unit.NewTargetPos - unit.position).sqrMagnitude<unit.neighbourRadius*unit.neighbourRadius*225/100) { unit.SetNewTargetPos(targetPos); } //unit.agent.TargetPos = unit._defaultTargetPos; } if (unit.AgentType == EAgentType.astar && unit.agent != null) { AStarAgent ag = unit.agent as AStarAgent; if (debugDrawPath) { for (int i = 1; i < ag._vecRunningPath.Count; i++) { UnityEngine.Debug.DrawLine(CustomMath.TsVecToVector3(ag._vecRunningPath[i - 1]), CustomMath.TsVecToVector3(ag._vecRunningPath[i]), UnityEngine.Color.green, 1); } } #if UNITY_EDITOR ag._showDebug = debugDrawPath; #endif _pathNodeIdx = ag.TowardPathIdx; _totalPathNodeCount = ag._vecRunningPath.Count; } }
//multi threads #if SEARCH_ENEMY public void FindTarget() { if (_nextCheckActionTime > _baseData.pfm.CurTime) { return; } int eCount = _listEnemyAgents.Count; //enemy in sight,either move to spec or AStar path finding if (eCount > 0 && _agentType == EAgentType.astar && !_pathBlocked && _agent != null) { AStarAgent aStarAgent = _agent as AStarAgent; _needRepath = aStarAgent.NeedRePath(); bool isFindingPath = aStarAgent.IsFindingPath(); for (int i = 0; i < eCount; i++) { IAgentBehaviour enemyAgent = _listEnemyAgents[i]; //closest enemy int idx = _map.GetGridNodeId(enemyAgent.position); FP curTargetDstSqr = (enemyAgent.position - position).sqrMagnitude; TSVector targetPos = enemyAgent.position; _targetPos = enemyAgent.position; if (_dicUnReachableAgents.Contains(idx) && _needRepath != ERepathType.hasOpen) // { if (eCount - 1 == i) //can't reach enemy agent,then walk to default target pos { targetPos = _defaultTargetPos; enemyAgent = null; _targetPos = _defaultTargetPos; idx = _map.GetGridNodeId(_defaultTargetPos); if (_dicUnReachableAgents.Contains(idx)) { _targetDistSqr = (_defaultTargetPos - _baseData.position).sqrMagnitude; //_nextCheckActionTime = _baseData.pfm.CurTime + 1000; // _dicUnReachableAgents.Clear();// return; } curTargetDstSqr = (_defaultTargetPos - _baseData.position).sqrMagnitude; } else { continue; } } bool bSameTarget = this.agent.TargetPos == targetPos; bool bNeedChangeTarget = !bSameTarget && curTargetDstSqr < _targetDistSqr - CustomMath.FPHalf; bool bToDefault = _targetPos == _defaultTargetPos; bool bNeedReFinding = _needRepath != ERepathType.none || !isFindingPath; bool canFind = _pathManager.CanFindPathNow(); if (!canFind) { _frameOffset = 30; } bool bNeedFindPath = ((bNeedChangeTarget && !bToDefault) || bNeedReFinding) && canFind; if (bNeedFindPath) //|| aStarAgent._asm==null { _aStarPathType = EAStarPathType.quickPath; _targetDistSqr = curTargetDstSqr; #if UNITY_EDITOR if (PathFindingManager.DEBUG) { if (_needRepath != ERepathType.none) { UnityEngine.Debug.Log("needrepath findpath"); } if (!isFindingPath) { UnityEngine.Debug.Log("not FindingPath findpath"); } if (bNeedChangeTarget && !bToDefault) { UnityEngine.Debug.Log("not bSameTarget findpath"); } } #endif break; } else if (bSameTarget) // && aStarAgent._asm != null same target and still finding the path,should't change target { break; } } _frameOffset = _frameOffset > 0 ? _frameOffset : 300; return; } if (eCount == 0) { if (_agentType == EAgentType.astar && _agent != null) { AStarAgent aStarAgent = _agent as AStarAgent; if (aStarAgent.IsNearTargetPos()) { _needRepath = aStarAgent.NeedRePath(); bool isFindingPath = aStarAgent.IsFindingPath(); bool bNeedReFinding = _needRepath != ERepathType.none || !isFindingPath; if (bNeedReFinding) //| { //_needRepath = true; _aStarPathType = EAStarPathType.quickPath; this.agent.StartPos = _baseData.position; this.agent.TargetPos = _defaultTargetPos; //TSVector pathEndPos = _pathManager.FindQuickPath(this.agent, this.agent.StartPos, this.agent.TargetPos, _map, false);// _targetPos = _defaultTargetPos; } } } } }
public ARequestHandler(AStarAgent agent, Vector3 start, Vector3 end) { Agent = agent; Start = start; End = end; }
void SpawnPieces() { AI = Instantiate <AStarAgent>(Resources.Load <AStarAgent>("Prefabs/AI"), new Vector3(startAIPos.x, startAIPos.y, 0), Quaternion.identity); AI.Initialize(this); }
// Use this for initialization void Start() { agent = GetComponent <AStarAgent>(); }