IEnumerator DoSomething() { Routine = true; yield return(new WaitForSeconds(TimeForNewPath)); GetNewPath(); validpath = navMeshAgent.CalculatePath(target, navpath); if (!validpath) { Debug.Log("no path"); validpath = navMeshAgent.CalculatePath(target, navpath); } yield return(new WaitForSeconds(RestTime)); Routine = false; }
// Calculates the distance of the target to npc. Compare the return value with sight range. public float CalculatePathLength(NavMeshAgent navMeshAgent, Vector3 targetPosition) { NavMeshPath path = new NavMeshPath(); if (navMeshAgent.enabled) { navMeshAgent.CalculatePath(targetPosition, path); } Vector3[] allWayPoints = new Vector3[path.corners.Length + 2]; allWayPoints[0] = entity.transform.position; allWayPoints[allWayPoints.Length - 1] = targetPosition; for (int i = 0; i < path.corners.Length; i++) { allWayPoints[i + 1] = path.corners[i]; } float pathLength = 0f; for (int i = 0; i < allWayPoints.Length - 1; i++) { pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]); } return(pathLength); }
public void onJump(int id) { if (5009 == id) {//死亡印记 if (m_linkProfessionRole.m_LockRole != null) { NavMeshPath path = new NavMeshPath(); NavMeshAgent nav = transform.GetComponent <NavMeshAgent>(); Vector3 pos = transform.position; int i = 2; for (; i <= 2 && i >= 0; i--) { Vector3 endPos = m_linkProfessionRole.m_LockRole.m_curModel.position + transform.forward * i; if (nav.CalculatePath(endPos, path)) { float dis = Vector3.Distance(pos, endPos); transform.DOJump(endPos, 0.2f * dis + endPos.y, 1, 0.01f); break; } } GameObject inst = GameObject.Instantiate(ASSASSIN_S1) as GameObject; inst.transform.SetParent(m_linkProfessionRole.m_LockRole.m_curModel, false); GameObject.Destroy(inst, 3f); } } m_linkProfessionRole.ShowAll(); }
IEnumerator ReserveSpawn() { _reserveCount++; yield return(new WaitForSeconds(Random.Range(0, _spawnTime))); GameObject obj = Managers.Game.Spawn(Define.WorldObject.Monster, monsterName); Vector3 randPos; NavMeshAgent nma = obj.GetOrAddComponent <NavMeshAgent>(); while (true) { Vector3 randDir = Random.insideUnitSphere * Random.Range(0, _spawnRadius); randDir.y = 0; randPos = _spawnPos + randDir; NavMeshPath path = new NavMeshPath(); if (nma.CalculatePath(randPos, path)) { break; } } obj.transform.position = randPos; _reserveCount--; }
private bool IsAltarReachable() { NavMeshPath _tryPath = new NavMeshPath(); _agent.CalculatePath(_altar.transform.position, _tryPath); float _pathDistance = 0; for (int i = 0; i < _tryPath.corners.Length; i++) { if (i + 1 < _tryPath.corners.Length) { _pathDistance += Vector3.Distance(_tryPath.corners[i], _tryPath.corners[i + 1]); } } if (_tryPath.status == NavMeshPathStatus.PathPartial) { return(false); } else if (_tryPath.status == NavMeshPathStatus.PathComplete && _pathDistance <= _maxDistance) { return(true); } else { return(false); } }
/// <summary> /// Generates the random positions and checks if they are validly placed on the navmesh /// </summary> /// <param name="a_iAmountOfPoints">The amount of patrol points</param> /// <param name="a_fRange">The range the points can be generated away from the center point</param> private void GeneratePositions(int a_iAmountOfPoints, float a_fRange) { for (int i = 0; i < a_iAmountOfPoints; i++) //Loop through the points { PatrolPoints ppPatrolPlaceholder = new PatrolPoints(); //Temporary placeholder to add later bool bCanReachTarget = false; //Can the point actually be reached while (bCanReachTarget == false) //Loop until point is valid { ppPatrolPlaceholder.SetRandomPos(m_v3PatrolCenter, a_fRange); //Get random position NavMeshPath nmpPath = new NavMeshPath(); //Create new nav path m_aAgentRef.CalculatePath(ppPatrolPlaceholder.m_v3PatrolPointPosition, nmpPath); // if (nmpPath.status == NavMeshPathStatus.PathPartial || nmpPath.status == NavMeshPathStatus.PathInvalid) //If path is not valid { Debug.Log("Bad Point"); } else { bCanReachTarget = true; } } ppPatrolPlaceholder.m_iIndex = i; //Set index of point m_lPatrolPointList.Add(ppPatrolPlaceholder); //Add it to list } }
IEnumerator NavTargetUpdate() { yield return(new WaitForSeconds(1.0f)); while (true) { NavMeshPath path = new NavMeshPath(); nav.CalculatePath(playerPos.position, path); if (path.status == NavMeshPathStatus.PathComplete) { if (!playerSpotted) { yield return(new WaitForSeconds(Random.Range(0.0f, 0.5f))); anim.SetTrigger("PlayerSpotted"); playerSpotted = true; spotDelay = 2.8f; } if (spotDelay <= 0) { nav.SetPath(path); } } yield return(new WaitForSeconds(navTargetRefreshDelay)); } }
public IEnumerator wander() { Vector3 newPos = RandomNavmeshLocation(wanderRadius); // gets random point on navmesh while (true) { NavMeshPath path = new NavMeshPath(); navMeshAgent.CalculatePath(newPos, path); if (path.status != NavMeshPathStatus.PathComplete) // checks to make sure that a path can be calcultaed with given random point { Debug.Log("Invalid path"); newPos = NavMeshUtils.RandomNavSphere(transform.position, wanderRadius, -1); } else { break; } } AICurrentTargetLocation = newPos; navMeshAgent.SetDestination(newPos); yield return new WaitUntil(() => Vector3.Distance(gameObject.transform.position, newPos) <= 0.25f); wanderCoroutine = null; }
public bool IsReachable(NavMeshAgent nmAgent, float radiusA, float radiusB) { if (this._pathForCalc == null) { this._pathForCalc = new NavMeshPath(); } bool flag1 = true; bool flag2; if (((Behaviour)nmAgent).get_isActiveAndEnabled()) { nmAgent.CalculatePath(this.Position, this._pathForCalc); flag2 = flag1 & this._pathForCalc.get_status() == 0; float num1 = 0.0f; Vector3[] corners = this._pathForCalc.get_corners(); for (int index = 0; index < corners.Length - 1; ++index) { float num2 = Vector3.Distance(corners[index], corners[index + 1]); num1 += num2; float num3 = this.CommandType != CommandType.Forward ? radiusB : radiusA; if ((double)num1 > (double)num3) { flag2 = false; break; } } } else { flag2 = false; } return(flag2); }
void ChaseTarget() { // Do not chase if currently attacking if (currentlyAttacking || blocking || takingDamage) { return; } // Walk towards target walking = true; // Find closest point on navmesh from the player controllers center, check if it is reachable NavMeshHit hit; NavMeshPath path = new NavMeshPath(); if (NavMesh.SamplePosition(playerPos, out hit, 2f, NavMesh.AllAreas)) { agent.CalculatePath(hit.position, path); if (path.status == NavMeshPathStatus.PathComplete) { agent.SetDestination(hit.position); } else { OutOfReach(); } } else { OutOfReach(); } }
void Fleeing() { //If the smoke grenade does not exist anymore if (go_SmokeAOE == null) { //Sets the ReturnToPost state SetNewState("ReturnToPost"); } else if (!SmokeGrenadeSeen) //If the smoke grenade hasn't been seen { //Calculate the distance between itself and the smoke grenade while ignoring the Y position float Distance = Vector3.Distance(new Vector3(transform.position.x, 1f, transform.position.z), new Vector3(go_SmokeAOE.transform.position.x, 1f, go_SmokeAOE.transform.position.z)); //If the distance is less than the maximum fleeing distance if (Distance < fl_NPC_FleeingDist) { //Calculate the direction between itself and the smoke grenade while ignoring the Y position Vector3 Direction = new Vector3(transform.position.x, 1f, transform.position.z) - new Vector3(go_SmokeAOE.transform.position.x, 1f, go_SmokeAOE.transform.position.z); //Calculate the new position Vector3 NewPosition = new Vector3(transform.position.x, 1f, transform.position.z) + Direction; //Set the target position to the new position v3_NPC_TargetPos = NewPosition; } //Create local variable for setting a new path NavMeshPath NewPath = new NavMeshPath(); //Calculate a path for the target position and store it in a variable nm_Agent.CalculatePath(v3_NPC_TargetPos, NewPath); //Replace the current path as the stored path nm_Agent.path = NewPath; } }
// Update is called once per frame void Update() { UnityEngine.Collider[] col = Physics.OverlapSphere(transform.position, 10f); if (col.Length > 0) { for (int i = 0; i < col.Length; i++) { Transform tf_Target = col[i].transform; if (tf_Target.name == "Player") { NavMeshPath path = new NavMeshPath(); agent.CalculatePath(tf_Target.position, path); Vector3[] wayPoints = new Vector3[path.corners.Length + 2]; wayPoints[0] = transform.position; wayPoints[wayPoints.Length - 1] = tf_Target.position; float _distance = 0f; for (int j = 0; j < path.corners.Length; j++) { wayPoints[j + 1] = path.corners[j]; _distance += Vector3.Distance(wayPoints[j], wayPoints[j + 1]); } if (_distance <= 10f) { agent.SetDestination(tf_Target.position); } } } } }
public override void OnBehaviourPlay(Playable playable, FrameData info) { NavMeshPath path = new NavMeshPath(); meshAgent.CalculatePath(destination.position, path); if (path.corners.Length < 2) { return; } Vector3 previousCorner = path.corners[0]; float lengthSoFar = 0.0f; int i = 1; while (i < path.corners.Length) { Vector3 currentCorner = path.corners[i]; lengthSoFar += Vector3.Distance(previousCorner, currentCorner); previousCorner = currentCorner; i++; } double navTime = lengthSoFar / meshAgent.speed; Debug.Log("NavTime: " + navTime); }
private void NavAgentPath() {//导航路径 整合 NavMeshPath path = new NavMeshPath(); navAgent.CalculatePath(targetPos, path); way = new Vector3[path.corners.Length]; for (int i = 0; i < path.corners.Length; i++) { way[i] = path.corners[i];//将用导航网格获得的路径关键点,添加到这个数组中 }//那么此时way这个数组中包含的就是从这个机器人当前位置 到目的位置 所要经过的所有关键点 //那么接下来 机器人导航按照上面所说的路径来 //先计算这个路径的总长度。用来判断是否到达目的地的关键要素 length = 0; for (int i = 0; i < way.Length - 1; i++) { length += (way[i + 1] - way[i]).magnitude;//计算两点之间的长度 } //for(int i = 0; i < way.Length; i++) //{ // print(way[i]); //} //l++; //print("way数组的长度" + way.Length); //print("遍历完"+l); }
//Move around player Function void CheckCover() { Debug.Log("funciona!"); float minDistance = 1000; float HidingSpotDistance; float playerToHideDistance; for (int i = 0; i < hidingPoints.Length; i++) { HidingSpotDistance = Vector3.Distance(transform.position, hidingPoints [i].transform.position); playerToHideDistance = Vector3.Distance(playerPos.position, hidingPoints [i].transform.position); if (HidingSpotDistance < minDistance && HidingSpotDistance > stopHidingRange && HidingSpotDistance < playerToHideDistance) { hideSpotPos = hidingPoints [i].transform.position; minDistance = Vector3.Distance(transform.position, hidingPoints [i].transform.position); } } if (minDistance < 1000) { bool checkpath; NavMeshPath myPath = new NavMeshPath(); checkpath = myNav.CalculatePath(hideSpotPos, myPath); if (myPath.status == NavMeshPathStatus.PathComplete) { StartGetCover(); } } }
/// <summary> /// Calculate the path to player using nav path /// </summary> /// <param name="targetPos"></param> /// <returns></returns> private float PathLength(Vector3 targetPos) { NavMeshPath path = new NavMeshPath(); if (nav.enabled) { nav.CalculatePath(targetPos, path); } Vector3[] allWayPoints = new Vector3[path.corners.Length + 2]; allWayPoints[0] = npcT.position; allWayPoints[allWayPoints.Length - 1] = targetPos; for (int i = 0; i < path.corners.Length; i++) { allWayPoints[i + 1] = path.corners[i]; } float pathLength = 0; for (int i = 0; i < allWayPoints.Length - 1; i++) { pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]); } return(pathLength); }
GameObject GetRetreatRedBase(BluePoliceSim threat) { GameObject selectedRedBase = simControlScript.RedBases[0]; float minRangeRatio = float.MaxValue; foreach (GameObject redBase in simControlScript.RedBases) { NavMeshPath thisPath = new NavMeshPath(); if (thisNavAgent.CalculatePath(redBase.transform.position, thisPath)) { float thisLength = PathLength(thisPath); float threatRange = threat.GetRangeTo(redBase); if (threatRange > 0f) { float thisRatio = thisLength / threatRange; if (thisRatio < minRangeRatio) { minRangeRatio = thisRatio; selectedRedBase = redBase; } } } } return(selectedRedBase); }
IEnumerator ReserveSpawn() { ++_reserveCount; yield return(new WaitForSeconds(UnityEngine.Random.Range(0, _spawnTime))); GameObject Obj = Managers.Game.Spawn(Define.eWorldObject.Monster, "Knight"); NavMeshAgent nma = Obj.GetComponent <NavMeshAgent>(); Vector3 randPos; while (true) { Vector3 randDir = Random.insideUnitSphere * Random.Range(0, _SpawnRadius); randPos.y = 0; randPos = _SpawnPosition + randDir; // 갈 수 있나 NavMeshPath path = new NavMeshPath(); if (nma.CalculatePath(randPos, path)) { break; } } Obj.transform.position = randPos; --_reserveCount; }
public NullableVector3 FindCover(Transform attacker, NavMeshAgent na, float coverCheckRadius, int numberOfChecks, LayerMask coverCriteria) { NullableVector3 cover = null; NavMeshPath coverPath = null; for (int i = 0; i < numberOfChecks; i++) { // Obtains a random position within a certain vicinity of the agent Vector3 randomPosition = ai.transform.position + Random.insideUnitSphere * coverCheckRadius; NavMeshHit coverCheck; // Checks if there is an actual point on the navmesh close to the randomly selected position if (NavMesh.SamplePosition(randomPosition, out coverCheck, na.height * 2, NavMesh.AllAreas)) { if (AIFunction.LineOfSight(coverCheck.position, attacker, coverCriteria) == false) // If line of sight is not established { // Ensures that the agent can actually move to the cover position. NavMeshPath newPathToTest = new NavMeshPath(); if (na.CalculatePath(coverCheck.position, newPathToTest)) { // Checks if the new cover position is easier to get to than the old one. if (cover == null || AIFunction.NavMeshPathLength(newPathToTest) < AIFunction.NavMeshPathLength(coverPath)) // Use OR statement, and check navmesh path cost between transform.position and the cover point currently being checked. { // If so, new cover position is established, and navmesh path is stored for next comparison cover = new NullableVector3(coverCheck.position); coverPath = newPathToTest; } } } } } return(cover); }
public float AgentWalkDistance(Vector3 start, Vector3 end, Color color) { //move agent to the start position Vector3 initialPosition = transform.position; _agent.Move(start - initialPosition); //test to see if agent has path or not float distance = Mathf.Infinity; NavMeshPath navMeshPath = _agent.path; if (!_agent.CalculatePath(end, navMeshPath)) { _agent.Move(initialPosition - start); return(distance); } Vector3[] path = navMeshPath.corners; if (path.Length < 2) { _agent.Move(initialPosition - start); return(distance); } //get walking path distance distance = 0; for (int i = 1; i < path.Length; i++) { distance += Vector3.Distance(path[i - 1], path[i]); Debug.DrawLine(path[i - 1], path[i], color); //visualizing the path, not necessary to return } _agent.Move(initialPosition - start); return(distance); }
public void CalculatePathAndMoveAgent() { agent = GetComponent <NavMeshAgent>(); agent.CalculatePath(finishPoint.transform.position, path); if (path.status == NavMeshPathStatus.PathComplete) { agent.SetDestination(finishPoint.transform.position); } else if (path.status == NavMeshPathStatus.PathInvalid) { print("Path invalid"); } else if (path.status == NavMeshPathStatus.PathPartial) { print("Path partial (GETTING BLOCKED)"); fntScript = GetComponent <FindNearestTurret>(); if (fntScript.target == null) { agent.SetDestination(finishPoint.transform.position); } else { Destroy(fntScript.target.gameObject); } } }
public static float WalkDistance(Vector3 to, NavMeshAgent usedAgent) { NavMeshPath path = new NavMeshPath(); usedAgent.CalculatePath(to, path); return(CalcPathDistance(path)); }
public void DetectNewObstacle(Vector3 obstaclePos) { //print ("method get called"); //print (Vector3.Distance (obstaclePos, transform.position)); if (Vector3.Distance(obstaclePos, this.transform.position) < detectRadius) { print("flee obj"); Vector3 fleeDirection = (transform.position - obstaclePos).normalized; Vector3 newGoal = this.transform.position + fleeDirection * fleeRadius; // creating a path must make sure the environment is baked NavMeshPath path = new NavMeshPath(); agent.CalculatePath(newGoal, path); if (path.status == NavMeshPathStatus.PathInvalid) { Debug.Log("Invalid Path"); } // path is not invalid then flee mother f****r if (path.status != NavMeshPathStatus.PathInvalid) { //Debug.Log (path.corners[0]); agent.SetDestination(path.corners[path.corners.Length - 1]); agent.speed = 20f; agent.angularSpeed = 500f; print("fleeing"); } } }
IEnumerator shootAndKill() { RaycastHit rh2; Debug.Log("preshot"); float gaa = Vector3.Distance(this.transform.position, target.position); Physics.Raycast(this.transform.position, target.position - this.transform.position, out rh2); Debug.DrawRay(this.transform.position + new Vector3(0, 2, 0), target.position - this.transform.position, Color.blue); Debug.Log("preshot2"); if ((rh2.transform.gameObject.tag == "Statute" || rh2.transform.gameObject.tag == "Player" || rh2.transform.gameObject.tag == "gate") && gaa < range) { Debug.Log("wszedl do shotu"); anim.SetInteger("controller", 2); nma.isStopped = true; Rigidbody tmp = Instantiate(rb, transsexualista.position, transsexualista.rotation); tmp.gameObject.GetComponent <Rigidbody>().AddForce(this.transform.forward * shootforce, ForceMode.Impulse); yield return(new WaitForSeconds(tor)); StartCoroutine(shootAndKill()); Debug.Log("postshot"); } else { Debug.Log("nie wszedl do shotu"); anim.SetInteger("controller", 1); Debug.Log(target.name); nma.CalculatePath(target.position, nmp); nma.path = nmp; yield return(new WaitForSeconds(tor)); StartCoroutine(shootAndKill()); Debug.Log("postnoshot"); } }
public void SetDestination(Vector3 destination) { //if(!canComputePath) return; NavMeshHit hit; if (!NavMesh.SamplePosition(destination, out hit, 30, NavMesh.AllAreas)) { Debug.LogWarning("Creature Die Because off of navmesh"); owner.Creature.Die(); return; } destination = hit.position; Destination = destination; if (!nav.isOnNavMesh) { Debug.LogWarning("Creature Die Because off of navmesh"); owner.Creature.Die(); return; } nav.CalculatePath(Destination, computingPath); //owner.StartCoroutine(WaitAndCanComputePath()); }
void Update() { SetAgentPosition(); if (Input.GetMouseButtonDown(0) && !Input.GetKey(KeyCode.LeftShift)) { var ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray.origin, ray.direction, out m_HitInfo)) { //m_Agent.destination = m_HitInfo.point; m_Path = new NavMeshPath(); endDestination = m_HitInfo.point; m_Agent.CalculatePath(endDestination, m_Path); pathIter = 1; m_Agent.isStopped = false; } } if (m_Path.corners == null || m_Path.corners.Length == 0) { return; } if (pathIter >= m_Path.corners.Length) { destination = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); m_Agent.isStopped = true; return; } else { destination = m_Path.corners[pathIter]; } if (destination.x < float.PositiveInfinity) { Vector3 direction = destination - AgentPosition; var newDir = Vector3.RotateTowards(transform.forward, direction, 50 * Time.deltaTime, 0.0f); var newRot = Quaternion.LookRotation(newDir); transform.rotation = Quaternion.Slerp(transform.rotation, newRot, Time.deltaTime * 2f); float distance = Vector3.Distance(AgentPosition, destination); if (distance > m_Agent.radius + 0.1) { Vector3 movement = transform.forward * Time.deltaTime * 2f; m_Agent.Move(movement); } else { ++pathIter; if (pathIter >= m_Path.corners.Length) { destination = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); m_Agent.isStopped = true; } } } }
public bool CanReachPosition(Vector3 position) { NavMeshPath path = new NavMeshPath(); navMeshAgent.CalculatePath(position, path); return(path.status == NavMeshPathStatus.PathComplete); }
//소리가 이동하는 총 거리를 계산합니다. float CalculatePathLength(Vector3 targetPosition) { NavMeshPath path = new NavMeshPath(); if (nav.enabled) { nav.CalculatePath(targetPosition, path); } //각 코너를 저장합니다. Vector3[] allWayPoints = new Vector3[path.corners.Length + 2]; //처음과 끝은 플레이어와 NPC의 위치 allWayPoints[0] = transform.position; allWayPoints[allWayPoints.Length - 1] = targetPosition; for (int i = 0; i < path.corners.Length; i++) { allWayPoints[i + 1] = path.corners[i]; } float pathLength = 0f; //거리를 더합니다 for (int i = 0; i < allWayPoints.Length - 1; i++) { pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]); } return(pathLength); }
void MoveCheck(Ray screenRay) { if (m_CalculatedPath.status == NavMeshPathStatus.PathComplete) { m_Agent.SetPath(m_CalculatedPath); m_CalculatedPath.ClearCorners(); } if (Physics.RaycastNonAlloc(screenRay, m_RaycastHitCache, 1000.0f, m_LevelLayer) > 0) { Vector3 point = m_RaycastHitCache[0].point; //avoid recomputing path for close enough click if (Vector3.SqrMagnitude(point - m_LastRaycastResult) > 1.0f) { NavMeshHit hit; if (NavMesh.SamplePosition(point, out hit, 0.5f, NavMesh.AllAreas)) {//sample just around where we hit, avoid setting destination outside of navmesh (ie. on building) m_LastRaycastResult = point; //m_Agent.SetDestination(hit.position); m_Agent.CalculatePath(hit.position, m_CalculatedPath); } } } }
public static float CalculatePathLength(Vector3 targetPosition, Vector3 originalPosition, GameObject originalObject) { NavMeshPath path = new NavMeshPath(); NavMeshAgent nav = originalObject.GetComponent <NavMeshAgent>(); if (nav.enabled) { nav.CalculatePath(targetPosition, path); } Vector3[] allWayPoints = new Vector3[path.corners.Length + 2]; allWayPoints[0] = originalPosition; allWayPoints[allWayPoints.Length - 1] = targetPosition; for (int i = 0; i < path.corners.Length; i++) { allWayPoints[i + 1] = path.corners[i]; } float pathLength = 0f; for (int i = 0; i < allWayPoints.Length - 1; i++) { pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]); } return(pathLength / 2); }