void Shooting() { NavMeshHit hit; if (agent.Raycast(target.transform.position, out hit)) { agent.SetDestination(target.transform.position); agent.speed = runningSpeed; } else if (!agent.Raycast(target.transform.position, out hit)) { time += Time.deltaTime; Quaternion arrowRota = Quaternion.LookRotation(target.transform.position - arrowPos.transform.position); Quaternion enemyRota = Quaternion.LookRotation(target.transform.position - transform.position); agent.speed = 0f; agent.transform.rotation = enemyRota; if (time > fireRate) { Instantiate(arrow, arrowPos.position, arrowRota); time = 0f; } } }
// TODO: handle PathInvalid cases public void Guide(Vector3 destination, List <Vector3> corners) { OkayToStop = false; agent.isStopped = false; originalDestination = destination; pathCorners = corners; nextCornerIndex = 0; for (int i = 1; i < corners.Count; i++) { Vector3 a = corners[i] - corners[i - 1]; Vector3 b = transform.position - corners[i - 1]; Vector3 c = transform.position - corners[i]; float dotBA = Vector3.Dot(b, a); float dotCA = Vector3.Dot(c, a); if (dotCA < 0) { if (dotBA >= 0) { nextCornerIndex = i; } break; } nextCornerIndex = i; } // Skip to the farthest unobstructed corner for (NavMeshHit hit; nextCornerIndex + 1 < corners.Count && !agent.Raycast(corners[nextCornerIndex + 1], out hit); nextCornerIndex++) { } }
private IEnumerator CheckPlayerInSight(float time = 2f) { yield return(new WaitForSeconds(time)); if (agent.Raycast(target.transform.position, out _)) { isPlayerInSight = false; } }
void GetNodesInView() { // get the nodes in agent's view NavMeshHit hit; foreach (GameObject node in nodes) { if (!agent.Raycast(node.transform.position, out hit)) // no obstacle { nodesInSight.Add(node); } } }
GameObject GetStudentInSight() { // find a studnet in sight to kill NavMeshHit hit; float angle; studentsInSight.Clear(); bool found = false; GameObject studentFound = null; foreach (GameObject student in studentsAlive) { if (student.GetComponent <Student>().life > 0) { if (student.GetComponent <Student>().isHiding()) { // Hiding students are not easy to find if (Random.Range(0, 2) == 1) { if (student != null && !agent.Raycast(student.transform.position, out hit)) // no obstacle. student is alive { angle = Vector3.Angle(student.transform.position - transform.position, transform.forward); if (angle < viewAngle / 2) { found = true; studentsInSight.Add(student); } } } } else { if (student != null && !agent.Raycast(student.transform.position, out hit)) // no obstacle. student is alive { angle = Vector3.Angle(student.transform.position - transform.position, transform.forward); if (angle < viewAngle / 2) { found = true; studentsInSight.Add(student); } } } } } if (!found) { return(null); } studentFound = studentsInSight[Random.Range(0, studentsInSight.Count)]; return(studentFound); }
// Update is called once per frame void Update() { Vector3 sumForces = Vector3.zero; int numForces = 0; foreach (Transform t in manager.boids) { float distance = Vector3.Distance(transform.position, t.position); if (distance <= repulsionRange && t != transform) { float factor = -(repulsionRange - distance) / repulsionRange; sumForces += (t.position - transform.position).normalized * factor * repulsionStrength; numForces++; } else if (distance <= alignmentRange) { sumForces += t.forward * alignementStrength; numForces++; } else if (distance <= attractionRange) { float factor = (distance - alignmentRange) / (attractionRange - alignmentRange); sumForces += (t.position - transform.position).normalized * factor * attractionStrength; numForces++; } } if (agent.Raycast(transform.position + Vector3.RotateTowards(velocity, transform.right, raycastAngle * Mathf.Deg2Rad, 0.0f), out rightHit)) { } if (agent.Raycast(transform.position + Vector3.RotateTowards(velocity, -transform.right, raycastAngle * Mathf.Deg2Rad, 0.0f), out leftHit)) { } if (numForces > 0) { sumForces /= (float)numForces; velocity += sumForces * Time.deltaTime; } transform.forward = velocity.normalized; velocity = Vector3.ClampMagnitude(velocity, maxSpeed); agent.Move(velocity * Time.deltaTime); }
private void SearchPlayer() { // Raycasting to player NavMeshHit hit; if (_agent.pathStatus != NavMeshPathStatus.PathInvalid) { if (_agent.Raycast(_target.position, out hit)) { // can't detect player if (_isChasing == true) { StartCoroutine("LostPlayer"); } _isChasing = false; } else { // detect player if (_isChasing == false) { ChangeState(_chaseState); } StopCoroutine("LostPlayer"); _isChasing = true; } } }
void DoRaycast() { if (_agent == null) { return; } NavMeshHit _NavMeshHit; bool _reachedBeforeTargetPosition = _agent.Raycast(targetPosition.Value, out _NavMeshHit); reachedBeforeTargetPosition.Value = _reachedBeforeTargetPosition; position.Value = _NavMeshHit.position; normal.Value = _NavMeshHit.normal; distance.Value = _NavMeshHit.distance; mask.Value = _NavMeshHit.mask; hit.Value = _NavMeshHit.hit; if (_reachedBeforeTargetPosition) { if (!FsmEvent.IsNullOrEmpty(reachedBeforeTargetPositionEvent)) { Fsm.Event(reachedBeforeTargetPositionEvent); } } else { if (!FsmEvent.IsNullOrEmpty(reachedAfterTargetPositionEvent)) { Fsm.Event(reachedAfterTargetPositionEvent); } } }
//this function is to spot other ai public void CanSeeAI() { Vector3 rayToCheck = objectToSeek.transform.position - transform.position + eyeLevel; //if the enemy is right next to us, we can see him if (rayToCheck.magnitude < mainParent.GetComponent <AIStateManager>().patrolManager.GetComponent <LocationManager>().criticalDistanceToWaypoint) { FoundCorrectObject(); } //if the object is wihtin our field of view if ((Vector3.Angle(rayToCheck, transform.forward)) < fieldOfView / 2f) { //Debug.DrawRay(transform.position, rayToCheck, Color.black); //test it using navmesh raycasting if (mainParent.GetComponent <AIMovementController>().useOwnNavSystem == false) { NavMeshHit hit2; if (!agent.Raycast(objectToSeek.transform.position + eyeLevel, out hit2)) { FoundCorrectObject(); } } } }
/// <summary> /// Gets a local line-of-sight position on the agent's navigation mesh. /// </summary> /// <remarks> /// <para> /// The minimum/maximum distance is used to control the desired travel range. /// But the minimum distance is a soft value. If an obstacle is hit before the desired /// minimum distance then hardMinimum is used to determine success or failure. So the /// true minimum is hardMinimum. E.g. I want to move a distance of between 10 and 20 /// in a random direction. If an obstacle is hit in the chosen direction, then fail if /// the distance is less than 1. /// </para> /// </remarks> /// <param name="navAgent"></param> /// <param name="minimumDistance">The desired minimimum distance.</param> /// <param name="maximumDistance">The maximum distance.</param> /// <param name="target"></param> /// <param name="hardMinimum">The absolute minimum distance. (Defaults to the NavMeshAgent radius.)</param> /// <returns></returns> public static bool GetRandomLocalTarget(this NavMeshAgent navAgent, float minimumDistance, float maximumDistance, out Vector3 target, float hardMinimum = -1) { var dist = Random.Range(minimumDistance, maximumDistance); var offset = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f)); target = navAgent.transform.position + offset.normalized * dist; NavMeshHit hit; navAgent.Raycast(target, out hit); if (hit.hit && hit.distance < dist) { target = hit.position; } hardMinimum = hardMinimum == -1 ? navAgent.radius : hardMinimum; if ((navAgent.transform.position - target).sqrMagnitude <= hardMinimum * hardMinimum) { target = Vector3.zero; return(false); } return(true); }
bool Find(Vector3 position, float range, float distance) { NavMeshHit hit; if (agent.Raycast(position, out hit)) { return(false); } if (hit.distance > distance) { return(false); } Vector3 normal = (hit.position - transform.position).normalized; Vector3 localNormal = Quaternion.Inverse(transform.rotation) * normal; if (localNormal.z <= 0) { return(false); } float r = Mathf.Atan2(localNormal.x, localNormal.z); if (Mathf.Abs(r) < range * 0.5) { return(true); } return(true); }
Vector3 getRandomPositionInNavMesh(){ List<Vector3> candidates = new List<Vector3>(); Vector3[] candidatesArray = candidates.ToArray(); while (candidates.Count == 0) { candidates = generateNCloseRandomPositions (50); float[] distances = getDistancesToTarget (candidates); NavMeshHit hit; //Debug.Log("Long lista: " + candidates.Count); for(int i = candidates.Count-1; i >0; i--){ if(Physics.Raycast(this.transform.position, candidates[i] - this.transform.position, 2)){ candidates.Remove(candidates[i]); continue; } if (!navMeshAgent.Raycast (candidates[i],out hit)) { candidates.Remove(candidates[i]); } } //Debug.Log("Long lista: " + candidates.Count); distances = getDistancesToTarget (candidates); candidatesArray = candidates.ToArray(); System.Array.Sort(distances,candidatesArray); } return candidatesArray[0]; }
// Checks if Player is visible using Raycast public void isPlayerVisible() { // Create a vector from the enemy to the player and store the angle between it and forward. Vector3 direction = targetObject.transform.position - transform.position; float angle = Vector3.Angle(direction, transform.forward); Debug.Log("ANGLE " + angle); // Create NavMesh hit var NavMeshHit hit; // If the Ray cast hits something other than the target, then true is returned, if not false // So !hit is used to specify visibility and... // If the angle between forward and where the player is, is less than half the angle of view... if (!navAgent.Raycast(targetObject.transform.position, out hit) && angle < fieldOfViewAngle * 0.5f) { // ... the player is Visible Debug.DrawLine(transform.position, targetObject.transform.position, Color.red); Debug.Log("Player is VISIBLE"); isVisible = true; // Update Close Text on Canvas canvasUpdate[0].enabled = true; } else { // ... the player is Not Visible isVisible = false; Debug.Log("Player is NOT VISIBLE"); // Update Close Text on Canvas canvasUpdate[0].enabled = false; } }
bool CanSeePlayer() { NavMeshHit hit; // true if didn't hit anything between the enemy and the player return(!navAgent.Raycast(player.position, out hit)); }
public override Status Update() { // Get the renderer if (m_Agent == null || m_Agent.gameObject != gameObject.Value) { m_Agent = gameObject.Value != null?gameObject.Value.GetComponent <NavMeshAgent>() : null; } // Validate members? if (m_Agent == null || target.Value == null) { return(Status.Error); } // Calcaulate the delayed timer NavMeshHit hit; Vector3 targetPos = target.transform.position; Vector3 currentPos = gameObject.transform.position; if (!m_Agent.Raycast(target.transform.position, out hit) && Vector3.Distance(currentPos, targetPos) < maxDistanceSight.Value && (Vector3.Dot(gameObject.transform.TransformDirection(localDirection.Value).normalized, (targetPos - currentPos).normalized) + 1f) * .5f >= 1f - maxAngleSight.Value) { // Send event? if (onSuccess.id != 0) { owner.root.SendEvent(onSuccess.id); } return(Status.Success); } else { return(Status.Failure); } }
/// <summary> /// Navigate towards the nearest Human, stopping when the Human is too far away or when they leave /// line of sight. /// </summary> /// <param name="target">Transform, the cloests enemy to the Zombie.</param> public void NavigateTowardsHuman(Transform target) { // Draw a ray from this gameobject to it's target. // If the ray collides with an object, its details are returned. // Reference: https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.Raycast.html NavMeshHit hit; // If this game object CAN see the target... if (!agent.Raycast(target.position, out hit)) { //Debug.Log("Target IS in sight."); agent.SetDestination(target.position); // If the target is further away than the chase distance... if (agent.remainingDistance > chaseDistance) { // Stop the Zombie agent.isStopped = true; agent.ResetPath(); //Debug.Log("Target is too far away. Distance: " + agent.remainingDistance); } } else { //Debug.Log("Target NOT in sight."); // Stop the Zombie agent.isStopped = true; agent.ResetPath(); } }
void Update() { if (enemyHealth.currentHealth > 0 && !enemyHealth.isDead && alarmSearch) { NavMeshHit hit; if (!nav.Raycast(player.position, out hit)) { playerVisible = true; } else { playerVisible = false; } if (enemyAttack.playerInRange && playerVisible) { transform.LookAt(player); nav.SetDestination(enemy.position); } else if (playerHealth.currentHealth > 0 && !enemyAttack.playerInRange || !playerVisible) { nav.SetDestination(player.position); } if (enemyHealth.isDead) { nav.enabled = false; } } }
void RayCast_Test() { NavMeshHit hit; if (_agent.Raycast(_HitInfo.point, out hit)) { //Debug.Log(hit.distance); } }
private Vector3 GetWanderDestination() { var randomAngle = Random.Range(0, Mathf.PI * 2); var target = transform.position + new Vector3(Mathf.Cos(randomAngle), 0, Mathf.Sin(randomAngle)) * wanderDistance; NavMeshHit hit; return(_agent.Raycast(target, out hit) ? hit.position : target); }
void Update() { NavMeshHit hit; if (!agent.Raycast(target.position, out hit)) { agent.SetDestination(hit.position); } }
public Vector3 GetClosestToNavMeshPoint(Vector3 point) { NavMeshHit hit; if (_agent.Raycast(point, out hit)) { return(hit.position); } return(point); }
public void Update() { NavMeshHit hit; m_isTargetObscured = m_agent.Raycast(Target, out hit); if (m_isTargetObscured && !m_linecasterRunning) { // If the target is not within line-of-sight and the line caster isn't running, start it up m_linecaster = StartCoroutine(CheckLinecast()); } else if (!m_isTargetObscured && m_linecasterRunning) { // If the target is within line-of-sight, stop the line caster and just beeline to the target m_linecasterRunning = false; m_usePathfinding = false; m_agent.ResetPath(); StopCoroutine(m_linecaster); } else if (!m_isTargetObscured) { // If target isn't obscured, beeline to target m_agent.ResetPath(); m_linecasterRunning = false; m_usePathfinding = false; } if (!m_usePathfinding) { NavMesh.SamplePosition(Target, out hit, m_agent.height, NavMesh.AllAreas); Vector3 dp = hit.position - transform.position; Vector3 direction = dp.normalized; Vector3 move = direction * m_agent.speed * Time.deltaTime; dest = hit.position; //if (dp.sqrMagnitude < move.sqrMagnitude) { // m_motion.Move(dp); //} else { m_motion.Move(move); //} dip = dp.magnitude; if (RotateToMovement && dp.magnitude > ROTATE_TO_MOVE_THRESHOLD) { Quaternion rot = Quaternion.LookRotation(Vector3.ProjectOnPlane(direction, Vector3.up), Vector3.up); Quaternion newRotation = Quaternion.Lerp(transform.rotation, rot, 10f * Time.deltaTime); transform.rotation = newRotation; } } }
static int Raycast(IntPtr L) { LuaScriptMgr.CheckArgsCount(L, 3); NavMeshAgent obj = LuaScriptMgr.GetNetObject <NavMeshAgent>(L, 1); Vector3 arg0 = LuaScriptMgr.GetNetObject <Vector3>(L, 2); NavMeshHit arg1 = LuaScriptMgr.GetNetObject <NavMeshHit>(L, 3); bool o = obj.Raycast(arg0, out arg1); LuaScriptMgr.Push(L, o); LuaScriptMgr.PushValue(L, arg1); return(2); }
static int Raycast(IntPtr L) { LuaScriptMgr.CheckArgsCount(L, 3); NavMeshAgent obj = (NavMeshAgent)LuaScriptMgr.GetUnityObjectSelf(L, 1, "NavMeshAgent"); Vector3 arg0 = LuaScriptMgr.GetVector3(L, 2); NavMeshHit arg1; bool o = obj.Raycast(arg0, out arg1); LuaScriptMgr.Push(L, o); LuaScriptMgr.PushValue(L, arg1); return(2); }
// Function that checks if the player is within range and in line of sight private bool IsPlayerInLineOfSight() { NavMeshHit hit; // Do raycast to player if (!_agent.Raycast(_playerTrans.position, out hit) && GetDistanceToPlayer() < _maxPursueDistance) { return(true); } else { return(false); } }
private bool CanSeeTarget() { if (target == null) { return(false); } NavMeshHit hitInfo; if (agent.Raycast(target.transform.position, out hitInfo)) { return(false); } return(true); }
private bool ISeeYou = false; //for player void EnemySight() { // direction is the target( player) location in the world 'compared' to this object's own position in the world Vector3 direction = target.position - transform.position; // angle is the angle this object is from the target float angle = Vector3.Angle(direction, transform.forward); //will need to be modified for player cover //add wall detection if (direction.magnitude < visDist && angle < visAngle) { NavMeshHit hit; if (!agent.Raycast(target.position, out hit)) { direction.y = 0; //turns towards player // Determine which direction to rotate towards Vector3 targetDirection = target.position - transform.position; // The step size is equal to speed times frame time. float singleStep = speed * Time.deltaTime; // Rotate the forward vector towards the target direction by one step Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f); // Draw a ray pointing at our target in Debug.DrawRay(transform.position, newDirection, Color.red); // Calculate a rotation a step closer to the target and applies rotation to this object if (beliefs.HasState("Aggressive") || beliefs.HasState("activated")) // if activated, show exclaimation text { transform.rotation = Quaternion.LookRotation(newDirection); ShowText(); } lastLocation.transform.position = target.transform.position; //end of enemy Rotate ISeeYou = true; } } else { ISeeYou = false; //turns off text when player is no longer seen } }
// void OnTriggerEnter(Collider other) { // if (other.gameObject.tag == this.tag && other.attachedRigidbody) { // // Debug.Log("it's not okay now " + other.gameObject.name); // } // } // void OnTriggerStay(Collider other) { // if (other.gameObject.tag == this.tag && other.attachedRigidbody) { // // GetComponent<NavMeshAgent>(); // // Vector3 direction = other.transform.position - this.transform.position; // // direction.Normalize(); // other.attachedRigidbody.AddForce((other.transform.position - this.transform.position) * 2); // isInCollide = true; // } // } // void OnTriggerExit(Collider other) { // // remove force when outside of the range // if (other.gameObject.tag == this.tag && other.attachedRigidbody) { // other.attachedRigidbody.velocity = Vector3.zero; // other.attachedRigidbody.angularVelocity = Vector3.zero; // isInCollide = false; // } // } // Update is called once per frame void Update() { NavMeshHit hit; if (agent.Raycast(target.position, out hit)) { lastSeen += Time.deltaTime; hasTargetInRange = false; if (lastSeen < 0.5f) { Reach(target.position, 0f); } } else { hasTargetInRange = true; GameObject[] enemyArray = GameObject.FindGameObjectsWithTag(this.tag); foreach (GameObject enemy in enemyArray) { foesMove enemyScript = enemy.GetComponent <foesMove>(); if (enemyScript) { enemyScript.follow(this.transform.position); } } Reach(target.position, 3f); lastSeen = 0f; } if (hasTargetInRange) { // GetComponent<Renderer>().material.color = Color.yellow; } else { // GetComponent<Renderer>().material.color = Color.black; } if (agent.remainingDistance < 3f) { agent.Stop(); if (hasTargetInRange) { this.transform.LookAt(target); } } else { Debug.DrawLine(this.transform.position, agent.destination); } }
/// <summary> /// 攻撃できるかどうかを判断する /// </summary> /// <returns></returns> bool IsAttack() { //自分とプレイヤーの距離を取得 float distance = Vector3.Distance(transform.position, playerPos); NavMeshHit hit; //自分と相手との距離が射程範囲内 かつ 自分と相手との間に障害物がない場合にture if (distance <= shotRange && !agent.Raycast(playerPos, out hit)) { return(true); } else { return(false); } }
// Update is called once per frame void FixedUpdate() { if (playS.inbox == true) { ChaseMd = false; playerVis = false; Physics.IgnoreCollision(GameObject.Find("Player").GetComponent <BoxCollider>(), GetComponent <Collider>()); } NavMeshHit hit; if (!NMA.Raycast(player.position, out hit)) { if (playS.inbox == false) { playerVis = true; } } else { playerVis = false; } if (Mode == 0) { RoamMd = true; ChaseMd = false; } if (Mode == 1) { RoamMd = false; ChaseMd = true; } if (RoamMd == true) { if (NMA.remainingDistance < 0.5) { int d = Random.Range(0, wps.Length); NMA.SetDestination(wps[d].transform.position); } } ChaseMode(); }