public CalculatePath ( Vector3 targetPosition, |
||
targetPosition | Vector3 | The final position of the path requested. |
path | The resulting path. | |
return | bool |
NavMeshPath CalculatePath(Vector3 position) { Vector3 fleeDirection, newGoal; NavMeshPath path; fleeDirection = (this.transform.position - position).normalized; newGoal = this.transform.position + fleeDirection * fleeRadius; path = new NavMeshPath(); _agent.CalculatePath(newGoal, path); while (path.status == NavMeshPathStatus.PathInvalid) { newGoal += fleeDirection; path = new NavMeshPath(); _agent.CalculatePath(newGoal, path); /*Debug.Log (newGoal); * Debug.Log (_xMin + " " + _xMax); * Debug.Log (_zMin + " " + _zMax);*/ if (newGoal.x < _xMin || newGoal.x > _xMax) { Debug.Log(newGoal + " X:" + _xMin + " " + _xMax); Debug.Log((newGoal.x < _xMin) + " " + (newGoal.x > _xMax)); return(null); } if (newGoal.z < _zMin || newGoal.z > _zMax) { Debug.Log((newGoal.z < _zMin) + " " + (newGoal.z > _zMax)); Debug.Log(newGoal + " Z:" + _zMin + " " + _zMax); return(null); } } _agent.CalculatePath(newGoal, path); return(path); }
public override bool IsDestinationNavigable(Vector3 destination) { // Debug.Log (destination + ":" + navigation); UnityEngine.AI.NavMeshPath path = new UnityEngine.AI.NavMeshPath(); navigation.CalculatePath(destination, path); return(path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete); }
protected void SetDestination() { //do this instead of setting agent.destination to force immediate path calculation UnityEngine.AI.NavMeshPath path = new UnityEngine.AI.NavMeshPath(); agent.CalculatePath(getRandomPositionOnNavMesh(), path); agent.path = path; }
//calculates the path distance between enemy and target float CalculatePathLength(Vector3 targetPosition) { //creates a new nav mesh path UnityEngine.AI.NavMeshPath path = new UnityEngine.AI.NavMeshPath(); //makes sure the navigation is there, and get path from agent if (Agent.enabled) { Agent.CalculatePath(targetPosition, path); } Vector3[] addedPatrolPoints = new Vector3[path.corners.Length + 2]; //set the first point to the enemy pos, and last point to target pos addedPatrolPoints[0] = transform.position; addedPatrolPoints[addedPatrolPoints.Length - 1] = targetPosition; //the loops sets all the inbetween values of the waypoints. So the first value will be enemy pos, second //value will be first patrol point or corner, for (int i = 0; i < path.corners.Length; i++) { addedPatrolPoints[i + 1] = path.corners[1]; } //tracks length float pathLength = 0f; //add calues of the lengths between patrols points for (int i = 0; i < addedPatrolPoints.Length - 1; i++) { pathLength += Vector3.Distance(addedPatrolPoints[i], addedPatrolPoints[i + 1]); } return(pathLength); }
float CalculatePathLength(Vector3 targetPosition) { // Create a path and set it based on a target position. UnityEngine.AI.NavMeshPath path = new UnityEngine.AI.NavMeshPath(); if (nav.enabled) { nav.CalculatePath(targetPosition, path); } // Create an array of points which is the length of the number of corners in the path + 2. Vector3 [] allWayPoints = new Vector3[path.corners.Length + 2]; // The first point is the enemy's position. allWayPoints[0] = transform.position; // The last point is the target position. allWayPoints[allWayPoints.Length - 1] = targetPosition; // The points inbetween are the corners of the path. for (int i = 0; i < path.corners.Length; i++) { allWayPoints[i + 1] = path.corners[i]; } // Create a float to store the path length that is by default 0. float pathLength = 0; // Increment the path length by an amount equal to the distance between each waypoint and the next. for (int i = 0; i < allWayPoints.Length - 1; i++) { pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]); } return(pathLength); }
float CalculatePathLength(Vector3 targetPosition) //soundpath { UnityEngine.AI.NavMeshPath path = new UnityEngine.AI.NavMeshPath(); if (nav.enabled) { nav.CalculatePath(targetPosition, path); } Vector3[] allWayPoints = new Vector3[path.corners.Length + 2]; 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); }
public bool findShortestPathToTile(UnityEngine.AI.NavMeshAgent agent, Vector3 position, out UnityEngine.AI.NavMeshPath path, out float shortestDistance) { //Try to find a path UnityEngine.AI.NavMeshPath[] paths = new UnityEngine.AI.NavMeshPath[4]; paths[0] = new UnityEngine.AI.NavMeshPath(); paths[1] = new UnityEngine.AI.NavMeshPath(); paths[2] = new UnityEngine.AI.NavMeshPath(); paths[3] = new UnityEngine.AI.NavMeshPath(); // Debug.Log (agent.gameObject.transform.position); // Debug.Log (position); //Calc paths to offseted target, check if complete, return shortest agent.CalculatePath(new Vector3(position.x, 0, position.z + 0.6f), paths[0]); //oben links agent.CalculatePath(new Vector3(position.x, 0, position.z - 0.6f), paths[1]); //unten rechts agent.CalculatePath(new Vector3(position.x + 0.6f, 0, position.z), paths[2]); //oben rechts agent.CalculatePath(new Vector3(position.x - 0.6f, 0, position.z), paths[3]); //unten links shortestDistance = Mathf.Infinity; int shortestIndex = 0; bool foundViablePath = false; for (int i = 0; i < 4; i++) { if (paths [i].status == UnityEngine.AI.NavMeshPathStatus.PathComplete) { float thisDistance = PathLength(paths [i]); Debug.Log("Path " + (i.ToString()) + " is viable. Length: " + thisDistance.ToString()); if (thisDistance < shortestDistance) { shortestDistance = thisDistance; shortestIndex = i; foundViablePath = true; } } } if (foundViablePath) { path = paths [shortestIndex]; return(true); } else { path = null; return(false); } }
public Vector3 RandomPath(Vector3 origin, float range) { Vector3 rando = new Vector3(Random.Range(-range, range) + origin.x, origin.y, Random.Range(-range, range) + origin.z); UnityEngine.AI.NavMeshPath path = new UnityEngine.AI.NavMeshPath(); agent.CalculatePath(rando, path); float dist = (rando - tran.position).sqrMagnitude; tries = 10; while (tries > 0 && (dist > maxDistanceSqrd || dist < minDistanceSqrd) || (path.status == UnityEngine.AI.NavMeshPathStatus.PathPartial)) { tries--; rando = new Vector3(Random.Range(-range, range) + origin.x, origin.y, Random.Range(-range, range) + origin.z); agent.CalculatePath(rando, path); dist = (rando - tran.position).sqrMagnitude; } return(rando); }
// Update is called once per frame void Update() { if (navMeshAgent.remainingDistance <= arrivalDistance) { SelectRandomDestination(); } navMeshAgent.CalculatePath(destination, navMeshPath); navMeshAgent.SetPath(navMeshPath); }
private void GoToNextPoint() { if (patrolPoints.Length > 0) { NavMeshPath dump = new NavMeshPath(); do { navAgent.destination = patrolPoints[nextPoint].position; nextPoint = ++nextPoint % patrolPoints.Length; } while (!navAgent.CalculatePath(patrolPoints[nextPoint].position, dump)); } }
public static Vector3 GetCanNavPos(UnityEngine.AI.NavMeshAgent nma, Vector3 targetPos) { UnityEngine.AI.NavMeshPath nmp = new UnityEngine.AI.NavMeshPath(); if (nma.enabled && nma.isOnNavMesh && nma.CalculatePath(targetPos, nmp)) { if (nmp.corners.Length > 1) { return(nmp.corners[nmp.corners.Length - 1]); } } return(Vector3.zero); }
public override void MoveTo(Vector3 v, bool needToAdjustPosY = true) { speed = 3f; isMovingToTarget = true; navAgent.speed = 0.0f; navAgent.SetDestination(v); path.ClearCorners(); navAgent.CalculatePath(v, path); cornersIdx = 1; moveDirection = (path.corners[cornersIdx] - transform.position).normalized; currentPathPointDistance = Vector3.Distance(transform.position, path.corners[cornersIdx]); }
public bool CanReachPosition(Vector3 dest) { Vector3 position = GTTools.NavSamplePosition(dest); mNavMeshAgent.enabled = true; mNavMeshAgent.CalculatePath(position, mNavMeshPath); if (mNavMeshPath.status != UnityEngine.AI.NavMeshPathStatus.PathPartial) { return(true); } return(false); }
public override bool run() { if (!sc.CalculatePath(sc.destination, new UnityEngine.AI.NavMeshPath())) { return(true); } if (Vector3.Distance(sc.transform.position, sc.destination) < 4) { return(true); } return(false); }
private Vector3 getRandomPosition() { Vector3 randomPosition; BoxCollider boxCollider = area != null?area.GetComponent <BoxCollider>() : null; if (boxCollider != null) { NavMeshPath path = new NavMeshPath(); int numIterations = 0; do { do { randomPosition = new Vector3(UnityEngine.Random.Range(area.transform.position.x - area.transform.localScale.x * boxCollider.size.x * 0.5f, area.transform.position.x + area.transform.localScale.x * boxCollider.size.x * 0.5f), UnityEngine.Random.Range(area.transform.position.y - area.transform.localScale.y * boxCollider.size.y * 0.5f, area.transform.position.y + area.transform.localScale.y * boxCollider.size.y * 0.5f)); }while (Vector2.Distance(randomPosition, target.transform.position) < closeDistance); navAgent.CalculatePath(randomPosition, path); Debug.Log("Iteration #" + numIterations + ": " + path.corners.Length + "corners"); numIterations++; }while (numIterations < 10 && CheckIfPathIntersectsPlayer(path)); if (numIterations >= 10) { navAgent.SetDestination(navAgent.transform.position); } navAgent.SetPath(path); return(randomPosition); } else { SphereCollider sphereCollider = area != null?area.GetComponent <SphereCollider>() : null; if (sphereCollider != null) { float distance = UnityEngine.Random.Range(-sphereCollider.radius, area.transform.localScale.x * sphereCollider.radius); float angle = UnityEngine.Random.Range(0, 2 * Mathf.PI); return(new Vector3(area.transform.position.x + distance * Mathf.Cos(angle), area.transform.position.y, area.transform.position.z + distance * Mathf.Sin(angle))); } else { return(gameObject.transform.position + new Vector3(UnityEngine.Random.Range(-5f, 5f), 0, UnityEngine.Random.Range(-5f, 5f))); } } }
void Update() { //Ray ray = new Ray(viewCamera.transform.position, viewCamera.transform.rotation * Vector3.forward); Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)); if (Physics.Raycast(ray, out hit, distanceRay, layers, QueryTriggerInteraction.Ignore)) { if (hit.transform.CompareTag("Chao") && coolDowndoGaze && incioJogo) { //inventarioUI.enabled = false; gazeTimer += Time.deltaTime; gaze.fillAmount = gazeTimer / 0.7f; if (gaze.fillAmount == 1) { if (agent.CalculatePath(hit.point, path)) { cursorHexagInstance.transform.position = hit.point; agent.SetDestination(hit.point); } coolDowndoGaze = false; StartCoroutine("CoolDownDoTimer"); GazeOff(); } } else if (hit.transform.CompareTag("Selecionavel")) { gazeTimer += Time.deltaTime; gaze.fillAmount = gazeTimer / totalTime; if (gaze.fillAmount == 1) { // somBotao.Play(); bt = hit.transform.gameObject.GetComponent <Button>(); bt.onClick.Invoke(); GazeOff(); } } else { GazeOff(); } } else { GazeOff(); } }
//计算到目标点的距离,若不能到达,则计算的是两点之间的距离 public static float CalculatePathLength(Vector3 _position, Vector3 targetPosition, UnityEngine.AI.NavMeshAgent _nav, UnityEngine.AI.NavMeshPath _path) { _path.ClearCorners(); allWayPoints.Clear(); UnityEngine.AI.NavMeshPath path = _path; if (_nav.enabled) { if (_path != null) { _nav.CalculatePath(targetPosition, _path); path = _path; } else { path = new UnityEngine.AI.NavMeshPath(); _nav.CalculatePath(targetPosition, path); } } allWayPoints.Add(_position); for (int i = 0; i < path.corners.Length; i++) { allWayPoints.Add(path.corners [i]); } allWayPoints.Add(targetPosition); float pathLength = 0; for (int i = 0; i < allWayPoints.Count - 1; i++) { pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]); } return(pathLength); }
// Return targetPosition if target is null private Vector3 Target() { NavMeshPath camino = new NavMeshPath(); if (navMeshAgent.CalculatePath(target.Value.transform.position, camino)) { ; } { } if (target.Value != null) { return(target.Value.transform.position); } return(targetPosition.Value); }
static int CalculatePath(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); UnityEngine.AI.NavMeshAgent obj = (UnityEngine.AI.NavMeshAgent)ToLua.CheckObject(L, 1, typeof(UnityEngine.AI.NavMeshAgent)); UnityEngine.Vector3 arg0 = ToLua.ToVector3(L, 2); UnityEngine.AI.NavMeshPath arg1 = (UnityEngine.AI.NavMeshPath)ToLua.CheckObject(L, 3, typeof(UnityEngine.AI.NavMeshPath)); bool o = obj.CalculatePath(arg0, arg1); LuaDLL.lua_pushboolean(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static public int CalculatePath(IntPtr l) { try { UnityEngine.AI.NavMeshAgent self = (UnityEngine.AI.NavMeshAgent)checkSelf(l); UnityEngine.Vector3 a1; checkType(l, 2, out a1); UnityEngine.AI.NavMeshPath a2; checkType(l, 3, out a2); var ret = self.CalculatePath(a1, a2); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public void DetectNewObstacle(Vector3 position) { if (Vector3.Distance(transform.position, position) <= detectionRadius) { Vector3 fleeDirection = (transform.position - position).normalized; Vector3 newGoal = transform.position + fleeDirection * fleeRadius; NavMeshPath path = new NavMeshPath(); agent.CalculatePath(newGoal, path); if (path.status != NavMeshPathStatus.PathInvalid) { agent.SetDestination(path.corners[path.corners.Length - 1]); anim.SetTrigger("isRunning"); agent.speed = 10; agent.angularSpeed = 500; } } }
// Update is called once per frame void Update() { if (target == null && !gettingTarget) { StartCoroutine(AcquireTarget()); } if (target != null) { if (myAgent.CalculatePath(target.transform.position, nextPath)) { if (nextPath.status == UnityEngine.AI.NavMeshPathStatus.PathPartial) { target = null; //Debug.Log("Partially blocked - Not reachable"); } else { myAgent.SetPath(nextPath); } } else { target = null; //Debug.Log("Not reachable"); } } if (inRange) { if (isBuilder) { //do rebuild RebuildNode(); } if (!isBuilder) { //do attack AttackTarget(); //Debug.Log("In attack range of player"); } } }
public override void Execute() { // create a Raycast and set it to the mouses cursor position in game Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, Mathf.Infinity, lm)) { path = new UnityEngine.AI.NavMeshPath(); if (agent.CalculatePath(hit.point, path)) { agent.SetPath(path); } else { path = null; } } }
// Will calculate a NavMeshPath on the NavMesh to the <targetPosition> and will // return the distance from start to end on the calculated NavMeshPath. private float GetPathDistance(Vector3 targetPosition, Color color) { UnityEngine.AI.NavMeshPath path = new UnityEngine.AI.NavMeshPath(); // Calculate the path to the <targetPosition>. navMeshAgent.CalculatePath(targetPosition, path); float distance = 0f; for (int i = 1; i < path.corners.Length; i++) { // Add-up to the total path distance. distance += Vector3.Distance(path.corners[i - 1], path.corners[i]); // Draw the path. Debug.DrawLine(path.corners[i - 1], path.corners[i], color); } return(distance); }
public void MoveTo(Vector3 location) { if (!location.Equals(Vector3.zero)) { NavMeshPath path = new NavMeshPath(); agent.CalculatePath(location, path); agent.SetPath(path); pathArray = path.corners; if (path.corners.Length > 2) { bMoving = true; currentPoint = 1; currentVector = path.corners[currentPoint]; } else { currentVector = path.corners[1]; } RpcMoveTo(currentVector); } }
// Update is called once per frame void Update() { if (fromTarget != null && toTarget != null && agent != null && line != null && agent.pathStatus != UnityEngine.AI.NavMeshPathStatus.PathInvalid) { line.enabled = true; transform.position = new Vector3(fromTarget.transform.position.x, transform.position.y, fromTarget.transform.position.z); agent.Warp(transform.position); transform.rotation = fromTarget.transform.rotation; path = new UnityEngine.AI.NavMeshPath(); agent.CalculatePath(toTarget.transform.position, path); line.SetVertexCount(path.corners.Length); Vector3[] destination = path.corners; for (int i = 0; i < destination.Length; i++) { destination[i] = new Vector3(destination[i].x, destination[i].y + tall, destination[i].z); } line.SetPositions(destination); //for (int i = 0; i < line.materials.Length; i++) { // if (i == 0) { // line.materials[i] = startLineMaterial; // } else if (i == line.materials.Length - 1) { // line.materials[i] = endLineMaterial; // } else { // line.materials[i] = normalLineMaterial; // } //} } if (toTarget == null) { line.enabled = false; } }
public void TakeCover() { //find cover if (!takingCover) { //m_oldpoint = m_waypoint; //get nearest cover int layerMask = 1 << 9; Collider[] coverSpots = Physics.OverlapSphere(transform.position, 30.0f, layerMask, QueryTriggerInteraction.Collide); float value = 200000.0f; foreach (Collider spot in coverSpots) { CoverSpot thisSpot = spot.GetComponent <CoverSpot>(); if (!thisSpot.InUse()) { UnityEngine.AI.NavMeshPath testPath = new UnityEngine.AI.NavMeshPath(); m_agent.CalculatePath(spot.transform.position, testPath); float tempDist = 0.0f; Vector3 prevCorner = testPath.corners[0]; for (int i = 1; i < testPath.corners.Length; i++) { Vector3 curCorner = testPath.corners[i]; float thisDist = Vector3.Distance(prevCorner, curCorner); tempDist += thisDist; if (Physics.Raycast(prevCorner, (curCorner - prevCorner), thisDist, (1 << 12))) { tempDist += 100.0f; } prevCorner = curCorner; } float newDanger = thisSpot.GetSquadDanger(); float shootable = 0.0f; if (thisSpot.IsLow()) { //shootable = 40.0f; } float closeTarget = 0.0f; if (m_target != null) { //closeTarget = Vector3.Distance(spot.transform.position, m_target.position) * 15.0f; } float newValue = (tempDist * 15.0f) + newDanger - shootable + closeTarget; if (newValue < value) { //Debug.Log(tempDist + " " + newDanger + " " + newValue); m_cover = spot.transform; value = newValue; } } } CoverSpot checkSpot = m_cover.GetComponent <CoverSpot>(); if (checkSpot != null) { checkSpot.SetUse(true); checkSpot.SetOwner(transform); inCover = 3000.0f; takingCover = true; holding = false; } } }
void PlayerDrawPath(bool setPath, Vector3 goalPos, bool drawToGoal) { int selected = 0; int firstSelect = -1; Color newColor = Color.clear; for (int i = 0; i < 3; i++) { if (playerSelect[i]) { selected++; newColor += colors[i]; if (firstSelect == -1) { firstSelect = i; } } } if (selected == 0) { return; } //Debug.Log(Time.time + " " + setPath + " " + goalPos + " " + drawToGoal); newColor /= (float)selected; UnityEngine.AI.NavMeshPath testPath = new UnityEngine.AI.NavMeshPath(); UnityEngine.AI.NavMeshAgent agent = playerSquad[firstSelect].GetComponent <UnityEngine.AI.NavMeshAgent>(); LineRenderer lineRenderer = gameObject.GetComponent <LineRenderer>(); Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits; RaycastHit tempHit; if (Physics.Raycast(ray, out tempHit) || drawToGoal) { Vector3 drawTo; if (drawToGoal) { drawTo = goalPos; } else { drawTo = tempHit.point; } agent.CalculatePath(drawTo, testPath); lineRenderer.positionCount = 0; if (testPath.corners.Length == 0) { placing = false; return; } //lineRenderer.SetPositions(testPath.corners); //lineRenderer.SetPosition(lineRenderer.positionCount, drawTo); lineRenderer.SetWidth(0.5f, 0.5f); lineRenderer.material.SetColor("_EmissionColor", newColor); int corners = 0; Vector3 prevCorner = testPath.corners[0]; Vector3 spawnPos = prevCorner; bool doorPlaced = false; lineRenderer.positionCount++; lineRenderer.SetPosition(corners, prevCorner); corners++; for (int i = 1; i < testPath.corners.Length; i++) { Vector3 curCorner = testPath.corners[i]; Vector3 dir = Vector3.Normalize((curCorner + Vector3.up) - (prevCorner + Vector3.up)); hits = Physics.RaycastAll(prevCorner, dir, Vector3.Distance(prevCorner, curCorner), (1 << 12)).OrderBy(h => h.distance).ToArray(); if (hits.Length == 0) { lineRenderer.positionCount++; lineRenderer.SetPosition(corners, curCorner); corners++; if (i >= testPath.corners.Length - 1 && setPath) { tempPos = curCorner; tempColor = newColor; if (doorPlaced) { m_gui.PlayerDoor(); } else { m_gui.PlayerMove(); } placing = true; } } else { foreach (RaycastHit hit in hits) { if (hit.collider.tag == "Objective") { i = 90000; lineRenderer.positionCount++; lineRenderer.SetPosition(corners, hit.point); corners++; if (setPath) { tempObjective = hit.collider.transform; tempPos = hit.point + new Vector3(0.0f, -1.0f); tempColor = newColor; placing = true; m_gui.PlayerObjective(); gameObject.GetComponent <LineRenderer>().positionCount = 0; } break; } if (doorPlaced && hit.collider.transform != tempDoor) { i = 90000; lineRenderer.positionCount++; lineRenderer.SetPosition(corners, hit.point); corners++; if (setPath) { tempPos = hit.point + new Vector3(0.0f, -1.0f); tempColor = newColor; placing = true; m_gui.PlayerDoor(); gameObject.GetComponent <LineRenderer>().positionCount = 0; } break; } else if (!doorPlaced) { if (i >= testPath.corners.Length - 1 && hits.Length == 1) { lineRenderer.positionCount++; lineRenderer.SetPosition(corners, curCorner); corners++; if (setPath) { tempPos = curCorner; tempColor = newColor; placing = true; m_gui.PlayerDoor(); gameObject.GetComponent <LineRenderer>().positionCount = 0; } } else { lineRenderer.positionCount++; lineRenderer.SetPosition(corners, hit.point); corners++; } doorPlaced = true; if (setPath) { tempDoor = hit.collider.transform; Vector3 doorPos = hit.point + new Vector3(0.0f, -1.0f); if (Vector3.Distance(doorPos, tempDoor.position + tempDoor.forward * 2.0f) > Vector3.Distance(doorPos, tempDoor.position - tempDoor.forward * 2.0f)) { tempSide = -2; } else { tempSide = 2; } } } } } prevCorner = curCorner; } } }
void DrawPath(bool setPath) { UnityEngine.AI.NavMeshPath testPath = new UnityEngine.AI.NavMeshPath(); UnityEngine.AI.NavMeshAgent agent = squad[squadSelect, 0].GetComponent <UnityEngine.AI.NavMeshAgent>(); Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { agent.CalculatePath(hit.point, testPath); Vector3 prevCorner = testPath.corners[0]; Vector3 spawnPos = prevCorner; float lifeSpan = 2.0f; for (int i = 1; i < testPath.corners.Length; i++) { Vector3 curCorner = testPath.corners[i]; Vector3 dir = Vector3.Normalize((curCorner + Vector3.up) - (prevCorner + Vector3.up)); for (float j = 0.0f; j < Vector3.Distance(prevCorner, curCorner); j += 1.0f) { if (!Physics.Raycast(prevCorner + (j - 1) * dir, dir, out hit, 1.0f, (1 << 12))) { if (!setPath) { PointMarker thisPoint = Instantiate(pointMarker, prevCorner + Vector3.Normalize(curCorner - prevCorner) * j, Quaternion.identity).GetComponent <PointMarker>(); thisPoint.SetLifespan(0.005f); thisPoint.SetColorMult(lifeSpan); thisPoint.SetColor(colors[squadSelect]); lifeSpan += 0.15f; } else if (j >= (Vector3.Distance(prevCorner, curCorner) - 1.0f) && i >= testPath.corners.Length - 1) { PointMarker thisPoint = Instantiate(pointMarker, prevCorner + Vector3.Normalize(curCorner - prevCorner) * j, Quaternion.identity).GetComponent <PointMarker>(); thisPoint.SetColumn(true, colors[squadSelect]); if (lastPoint[squadSelect] != null) { Destroy(lastPoint[squadSelect].gameObject); } lastPoint[squadSelect] = thisPoint.transform; SquadMove(thisPoint.transform); } } else { i = 90000; if (setPath) { PointMarker thisPoint = Instantiate(pointMarker, prevCorner + Vector3.Normalize(curCorner - prevCorner) * (j - 1.0f), Quaternion.identity).GetComponent <PointMarker>(); thisPoint.SetColumn(true, colors[squadSelect]); if (lastPoint[squadSelect] != null) { Destroy(lastPoint[squadSelect].gameObject); } lastPoint[squadSelect] = thisPoint.transform; SquadMove(thisPoint.transform); } break; } } prevCorner = curCorner; } } }
// Update is called once per frame void Update() { UnityEngine.AI.NavMeshAgent agent = GetComponent <UnityEngine.AI.NavMeshAgent>(); float velocity = agent.velocity.magnitude; if (velocity > 2.0f) { footesteps.UnPause(); } else { footesteps.Pause(); } if (destCandle != null) { // Check if we've reached the destination if (!agent.pathPending) { if (agent.remainingDistance <= agent.stoppingDistance) { if (canDestroy != false) { if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f) { destCandle.LightOff(); destCandle = null; } } } } } // Get all candles that are burning Candle[] candles = GameObject.FindObjectsOfType <Candle>().Where(c => c.IsLightOn()).ToArray(); // For each candle calc distance and figure out the minimum float minDist = float.PositiveInfinity; Candle minCandle = null; foreach (Candle c in candles) { UnityEngine.AI.NavMeshPath path = new UnityEngine.AI.NavMeshPath(); agent.CalculatePath(c.transform.position, path); // only of candle is reachable if (path.status != UnityEngine.AI.NavMeshPathStatus.PathComplete) { print("Error: a candle is not reachable by AI"); } else { float dist = GetPathLength(path); if (dist < minDist) { minDist = dist; minCandle = c; } } } // Set agents destination if (minCandle) { agent.destination = minCandle.transform.position; destCandle = minCandle; } }