void TCRetOverrideBehaviour() { //Go To TC If not close enough TCdropOff = GetAdjustedPos(TC); if (Vector3.Distance(transform.position, TCdropOff) > attackRange) { NavMeshPath path = new NavMeshPath(); if (idle) { agent.CalculatePath(TCdropOff, path); agent.SetPath(path); Resume(); } } //Deposit and toggle off override else { if (currentInv > 0) { //Find gamemanager and update resources GM.UpdateResourceCount((int)objID.ownerPlayerID, currentInv); currentInv = 0; } TCRetOverride = false; } }
/// <summary> /// CUrrently handles the movement logic for the hunter. ///</summary> void Update() { // If the RMB is held down or the nav mesh has a path, set the // path, redraw the line following the navMeshAgent's path, and // change the line's color. if (Input.GetMouseButtonDown(1) || navMeshAgent.hasPath) { navMeshAgent.SetPath(path); drawLinePath(navMeshAgent.path); pathLineRenderer.endColor = Color.black; pathLineRenderer.startColor = pathLineRenderer.endColor; // If the nav mesh does not have a path, set the destination // indicator, calculate the nav destination using the // destination indicator's position, draw the line, and // chang ethe line's color. } else { setDestinationIndicator(); calculateNavDestination(destinationIndicator. transform.position); drawLinePath(path); pathLineRenderer.endColor = Color.white; pathLineRenderer.startColor = pathLineRenderer.endColor; } }
//public void HandleMouse() //{ // RaycastHit[] hits = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition), 100f); // Debug.Log("Attempting mouse handle for: " + hits.Length); // if (hits.Length > 0) // { // foreach (RaycastHit hit in hits) // { // Debug.Log("Hit: " + hit.transform.gameObject.name); // if (hit.transform.gameObject.CompareTag("Enemy")) // { // Debug.Log("Hit Enemy"); // NavMeshHit nearestHit = new NavMeshHit(); // NavMesh.SamplePosition(hit.point, out nearestHit, 10f, NavMesh.AllAreas); // playerAgent.CalculatePath(nearestHit.position, playerPath); // playerAgent.SetPath(playerPath); // break; // } // else if (hit.transform.gameObject.CompareTag("Ground")) // { // //If it hit ground, try to calculate path to hit point, if so, go, otherwise calculate path to closest point // if (!playerAgent.CalculatePath(hit.point, playerPath)) // { // NavMeshHit nearestHit = new NavMeshHit(); // NavMesh.SamplePosition(hit.point, out nearestHit, 10f, NavMesh.AllAreas); // playerAgent.CalculatePath(nearestHit.position, playerPath); // playerAgent.SetPath(playerPath); // } // else // { // playerAgent.SetPath(playerPath); // } // } // } // } //} public void HandleMouseDown() { //Raycast to objects RaycastHit[] hits = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition), 100f); //Check raycast hits if (hits.Length > 0) { foreach (RaycastHit hit in hits) { //If it hit ground, try to calculate path to hit point if (hit.transform.gameObject.CompareTag("Ground")) { if (!playerAgent.CalculatePath(hit.point, playerPath)) { NavMeshHit nearestHit = new NavMeshHit(); NavMesh.SamplePosition(hit.point, out nearestHit, 10f, NavMesh.AllAreas); playerAgent.CalculatePath(nearestHit.position, playerPath); playerAgent.SetPath(playerPath); } else { playerAgent.SetPath(playerPath); } } } } }
public void UpdateChasing() { if (!DetectionArea.ContainsPlayer) { //Stop chasing if player leaves SetMoving(); } else if (Vector3.Distance(transform.position, playerTransform.position) < AttackRange) { //Start attacking if player in range SetAttacking(); } else { //Update path if player still needs chasing NavMeshPath path = new NavMeshPath(); if (Agent.CalculatePath(playerTransform.position, path) && path.status == NavMeshPathStatus.PathComplete) { Agent.SetPath(path); } else { SetMoving(); //Reset to moving if we can't reach the player (this will be repeatedly called each frame but it's probably fine...) } } }
public void SetPath(IPath path) { if (object.ReferenceEquals(_agent, null)) { throw new System.InvalidOperationException("UnityPathAgent was not configured correctly."); } if (!(path is UnityPath)) { throw new PathArgumentException(); } _agent.SetPath((path as UnityPath).NavMeshPath); }
public override void OnEnter() { if (duration <= 0) { Finish(); return; } if (navMeshAgent.isStopped) { navMeshAgent.isStopped = false; } navMeshAgent.SetPath(CalcNextPos(wanderRadius)); }
public void moveToPosition(ArenaTile tile) { Vector3 pos = tile.transform.position; NavMeshPath path = new NavMeshPath(); navMesh.CalculatePath(pos, path); if (path.status == NavMeshPathStatus.PathComplete) { navMesh.SetPath(path); if (currentTile != null) { currentTile.tile = null; } currentTile = tile; tile.tile = this; movement = true; } else { Debug.Log("Cannot reach destination.", gameObject); selected = false; } }
private IEnumerator StateRun() { //настройка состояния CurrentState = EnemyState.RUN; _agent.isStopped = false; //само состояние while (CurrentState == EnemyState.RUN) { if (!_agent.hasPath) { if (_pathMesh.MoveNext()) { _agent.SetPath(_pathMesh.Current); } else //дошли до конца { Destroy(gameObject); } } else { OnRun.Invoke(); } yield return(null); } if (CurrentState == EnemyState.ATTACK) { StartCoroutine(StateAttack()); } }
public void Update() { if (behavior == null) { Behavior = eSteeringBehavior.Idle; } if (computingPath.status == NavMeshPathStatus.PathComplete) { if (!nav.isOnNavMesh) { Debug.LogWarning("Creature Die Because off of navmesh"); owner.Creature.Die(); return; } nav.SetPath(computingPath); computingPath = new NavMeshPath(); } Evades.RemoveAll(agent => agent == null); Velocity = nav.velocity; behavior.Update(owner); if (owner.Debug) { Vector3[] path = nav.path.corners; for (int i = 0; i < path.Length - 1; ++i) { Debug.DrawLine(path[i], path[i + 1], Color.red); } } }
public void resume() { player.velocity = lastAgentVelocity; thief.velocity = lastAgentVelocity; player.SetPath(lastAgentPath); thief.SetPath(lastAgentPathThief); }
void resume() { if (agent.enabled) { agent.velocity = lastAgentVelocity; if (lastAgentPath == null) { moveTo(nextDestination); } else { agent.SetPath(lastAgentPath); } } agentPaused = false; }
private IEnumerator UpdateDestination() { while (!isDead) { //Calculate and visualize the target position. Vector3 targetPosition = AI_Utilities.GetTargetNextFramePosition(transform.position, target.position, motor.data.controller.velocity); Debug.DrawLine(transform.position, targetPosition, Color.red, 0.15f); //Calculate a path to the player's next frame position. NavMeshPath path = new NavMeshPath(); NavMesh.CalculatePath(transform.position, targetPosition, NavMesh.AllAreas, path); //Update the destination. if (path.status == NavMeshPathStatus.PathComplete) { agent.SetPath(path); } else { agent.SetDestination(target.position); } //Calculate the distance to the target and check if the enemy is in attack range. float distanceToTarget = Vector3.Distance(transform.position, target.position); isInAttackRange = (distanceToTarget < attackDistance); agent.updateRotation = !isInAttackRange; //Match the animation speed to the movement. float moveMagnitude = new Vector2(agent.velocity.x, agent.velocity.z).magnitude / agent.speed; animator.SetFloat("MoveMagnitude", Mathf.Clamp01(moveMagnitude)); //Delay the next update. yield return(new WaitForSeconds(0.15f)); } }
//---------------------------------------------------------------------- //! @brief パスの設定 //! //! @param[in] ナビメッシュパス //! //! @return なし //---------------------------------------------------------------------- public void SetPath(NavMeshPath path) { if (GetUseNavMesh()) { m_navMeshAgent.SetPath(path); } }
public override TaskStatus OnUpdate() { transform.forward = direction.Value; Vector3 move = _owner.Speed * direction.Value * Time.deltaTime; move.y = -10; //characterController.Move(move); bool hasPath = agent.CalculatePath(target.Value, path); if (path.status == NavMeshPathStatus.PathComplete && path.corners.Length > 0) { agent.SetPath(path); agent.avoidancePriority = 50; } else { agent.avoidancePriority = 40; target.Value = transform.position; return(TaskStatus.Failure); } //agent.SetDestination(target.Value); animator.SetBool("bAttack", false); animator.SetBool("bMoving", true); return(TaskStatus.Success); }
void Start() { NavMesh.avoidancePredictionTime = 5f; //Disable automatic agent movement so that we can apply it's desired velocity in Tick(); //navAgent.isStopped = true; //if(terminalGoal == null) terminalGoal = GameObject.FindGameObjectWithTag("Goal").transform; if (path == null) { GameObject go = GameObject.FindGameObjectWithTag("Goal"); if (go != null) { Debug.LogWarning($"{typeof(LegacyPedestrianAgent)} was not properly initialised with a {nameof(path)}!, must call {nameof(TrySetGoal)} before {nameof(Start)}", this); if (TrySetGoal(go.transform.position)) { Debug.Log($"{typeof(LegacyPedestrianAgent)} found a backup goal {go} by tag", this); } else { Debug.LogWarning($"{typeof(LegacyPedestrianAgent)} could not find a backup goal {go} by tag", this); } } } if (path != null) { navAgent.SetPath(path); } }
private Status RecalculatePath() { if (toGameObject) { Vector3 target = toGameObject.transform.position; targetPosAtLastPathing = target; path = new NavMeshPath(); navMeshAgent.CalculatePath(target, path); if (path.status == NavMeshPathStatus.PathComplete) { // If the actual end position is too far away from the desired // end position we consider our movement a failure. Vector3 pathEnd = path.corners[path.corners.Length - 1]; if (GroundDistance(target, pathEnd) < 0.1f) { if (navMeshAgent.SetPath(path) && navMeshAgent.hasPath) { return(Status.Running); } else { return(Status.Success); } } } } // Failure path = new NavMeshPath(); return(Status.Failure); }
public void Set(NavMeshAgent target) { neargate = FindClosestGate(); NavMesh.CalculatePath(gameObject.transform.position, neargate.transform.position, NavMesh.AllAreas, path1); target.destination = neargate.transform.position; target.SetPath(path1); }
private bool SetDestination(Vector3 destination) { bool flag = false; NavMeshAgent navMeshAgent = this.Agent.NavMeshAgent; if (!navMeshAgent.get_isOnNavMesh() || !navMeshAgent.get_path().get_corners().IsNullOrEmpty <Vector3>()) { return(flag); } if (this._path == null) { this._path = new NavMeshPath(); } if (navMeshAgent.CalculatePath(destination, this._path)) { if (this._path.get_status() != null) { this._rejected = true; } if (!navMeshAgent.SetPath(this._path)) { ; } } return(flag); }
private IEnumerator Follow(float maxRange) { while (Target != null) { Vector3 position = Target.transform.position; if (Vector3.Distance(position, previousPosition) > followDifference) { previousPosition = position; SetNavMeshAgent(position, maxRange - 2); navMeshAgent.SetPath(path); } yield return(null); } }
void moveTowards(Vector3 targetPos) { NavMeshPath navMeshPath = new NavMeshPath(); navMeshAgent.CalculatePath(targetPos, navMeshPath); navMeshAgent.SetPath(navMeshPath); }
public override Status Update() { timer += Time.deltaTime; if (timer >= wanderTime) { Vector3 wanderPos = RandomNavSphere(owner.root.transform.position, wanderRadius); agent.SetDestination(wanderPos); timer = 0; NavMeshPath path = new UnityEngine.AI.NavMeshPath(); bool success = agent.CalculatePath(wanderPos, path); if (success) { agent.SetPath(path); return(Status.Success); } else { Debug.LogError("No path found."); return(Status.Failure); } } return(Status.Success); }
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); } } } }
// Use this for initialization void Start() { nav = GetComponent <NavMeshAgent>(); path = new NavMeshPath(); nav.CalculatePath(GameObject.FindGameObjectWithTag("EndPoint").transform.position, path); nav.SetPath(path); }
void DoSetPath() { if (_pathProxy == null || _agent == null) { return; } bool _ok = _agent.SetPath(_pathProxy.path); pathAssigned.Value = _ok; if (_ok) { if (!FsmEvent.IsNullOrEmpty(pathAssignedEvent)) { Fsm.Event(pathAssignedEvent); } } else { if (!FsmEvent.IsNullOrEmpty(pathNotAssignedEvent)) { Fsm.Event(pathNotAssignedEvent); } } }
// Update is called once per frame void Update() { if (Vector3.Distance(agent.destination, routePoints[routeDestinationIndex].transform.position) >= 1) //if you are not currently going to where you're supposed to be going { bool isAccesable = NavMesh.CalculatePath(transform.position, routePoints[routeDestinationIndex].transform.position, NavMesh.AllAreas, path); if (isAccesable) //if it is possible to go to where you're supposed to be going { agent.SetPath(path); } else { routeDestinationIndex++; if (routeDestinationIndex > routePoints.Length - 1) { routeDestinationIndex = 0; } } } if (Vector3.Distance(transform.position, routePoints[routeDestinationIndex].transform.position) <= 1)//if you have arrived at your destinatation { routeDestinationIndex++; if (routeDestinationIndex > routePoints.Length - 1) { routeDestinationIndex = 0; } } //if the car is flipped over then disable it if (Mathf.Abs(transform.eulerAngles.z) > 30) { Destroy(GetComponent <vehicleRouteNavigation>()); } }
// Set nav target, generates a path // Returns true on valid path, false otherwise public bool SetTarget(Vector3 target) { NavMeshHit nvh; if (NavMesh.SamplePosition(target, out nvh, 1.0f, NavMesh.AllAreas)) { // New Path NavMeshPath newPath = new NavMeshPath(); // Generate a path, and if one exists: if (agent.CalculatePath(nvh.position, newPath)) { if (newPath.status == NavMeshPathStatus.PathComplete) { // Set the goal targetLocation = target; // Set the path targetPath = newPath; agent.SetPath(targetPath); return(true); } } } return(false); }
public void Move(Vector3 velocity) { if (myNavMeshAgent.enabled && !myNavMeshAgent.isOnOffMeshLink) { this.velocity = velocity; if (myNavMeshAgent.velocity.sqrMagnitude > minimumSqrSpeed) { OnAnimateMovement?.Invoke(); } else { OnAnimateIdle?.Invoke(); } pathTransformPosition += velocity * Time.deltaTime; myPathTransform.position = pathTransformPosition; if (Vector3.SqrMagnitude(myPathTransform.position - transform.position) > 1f) { if (myNavMeshAgent.CalculatePath(myPathTransform.position, path)) { myNavMeshAgent.SetPath(path); } } } }
public virtual void Pursuing() { // Gets the enemy destination. Vector3 destination; if (HasTargetSight()) { destination = target.transform.position; } else { destination = lastTargetLocation; } // Ensures destination is on the NavMesh. NavMeshHit navHit; if (NavMesh.SamplePosition(destination, out navHit, 50.0f, agent.areaMask)) { // Tries getting a path to the destination. NavMeshPath path = GetPath(navHit.position); if (path.status != NavMeshPathStatus.PathComplete && isMeeleAttack) { agent.SetDestination(originalPosition); // Returns to original position if unable to reach and out of range. } else { agent.SetPath(path); } } else // Returns to original position if unable to reach. { agent.SetDestination(originalPosition); } }
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 void Inspect(Vector3 position) { state = State.Inspect; navMeshAgent.speed = 2f; // Navigate to position NavMeshPath navPath = new NavMeshPath(); navMeshAgent.CalculatePath(position, navPath); if (navPath.status == NavMeshPathStatus.PathComplete) { navMeshAgent.SetPath(navPath); } // If position isn't available, navigate to the nearest door instead else { Bars barBest = null; float barBestDistance = Mathf.Infinity; foreach (Bars bar in GameController.main.bars) { float barDistance = Vector3.Distance(transform.position, bar.transform.position); if (barDistance < barBestDistance) { barBest = bar; barBestDistance = barDistance; } } navMeshAgent.SetDestination(barBest.transform.position); } }