void ClearGoalNode() { goalNode = null; path = null; navMesh = null; manager[moveBehavior].SetEnabled(false); }
public WowMapPather(string continent) { fullFileName = continent; Continent = continent.Substring(continent.LastIndexOf('\\') + 1); if (Directory.Exists(continent)) _meshPath = continent; else { var assembly = Assembly.GetCallingAssembly().Location; var dir = Path.GetDirectoryName(assembly); if (Directory.Exists(dir + "\\Meshes")) _meshPath = dir + "\\Meshes\\" + continent; else _meshPath = dir + "\\" + continent; } if (!Directory.Exists(_meshPath)) throw new Exception("No mesh for " + continent + " (Path: " + _meshPath + ")"); _mesh = new NavMesh(); DetourStatus status; // check if this is a dungeon and initialize our mesh accordingly string dungeonPath = GetDungeonPath(); if (File.Exists(dungeonPath)) { var data = File.ReadAllBytes(dungeonPath); status = _mesh.Initialize(data); IsDungeon = true; } else status = _mesh.Initialize(32768, 4096, Utility.Origin, Utility.TileSize, Utility.TileSize); if (status.HasFailed()) throw new Exception("Failed to initialize the mesh"); // _query = new NavMeshQuery(new PatherCallback(this)); //TODO: Add Callback for Dynamic Tile Loading _query = new NavMeshQuery(); _query.Initialize(_mesh, 65536); Filter = new QueryFilter { IncludeFlags = 0xFFFF, ExcludeFlags = 0x0 }; }
public FloodFill(NavMesh mesh) { Mesh = mesh; _query = new NavMeshQuery(); if (!_query.Initialize(Mesh, 1024).HasSucceeded()) throw new Exception("Failed to initialize navigation mesh query"); _filter = new QueryFilter(); var param = Mesh.Parameter; // detour guarantees these are 2^x var tileBits = (int) Math.Log(param.MaxTiles, 2); var polyBits = (int) Math.Log(param.MaxPolygons, 2); // we also don't care about salt, so create a mask to cut these off just in case Visited = new bool[1 << (tileBits + polyBits)]; VisitedMask = (1 << (tileBits + polyBits)) - 1; _open = new Queue<uint>(100); }
protected override void LoadContent() { _mesh = new NavMesh(); if (File.Exists(@"S:\meshReader\meshes\" + _continent + "\\" + _continent + ".dmesh")) { _mesh.Initialize(File.ReadAllBytes(@"S:\meshReader\meshes\" + _continent + "\\" + _continent + ".dmesh")); } else { _mesh.Initialize(32768, 128, World.Origin, Constant.TileSize, Constant.TileSize); MeshTile discard; _mesh.AddTile( File.ReadAllBytes(@"S:\meshReader\meshes\" + _continent + "\\" + _continent + "_" + _tileX + "_" + _tileY + ".tile"), out discard); } float[] vertices; int[] tris; _mesh.BuildRenderGeometry(_tileX, _tileY, out vertices, out tris); _drawer = new GeometryDrawer(); _drawer.Initialize(Game, new Color(0.1f, 0.1f, 0.9f, 0.5f), vertices, tris); _effect = new BasicEffect(GraphicsDevice); _depthState = new DepthStencilState { DepthBufferEnable = true }; }
// Update is called once per frame void Update() { distanceToPlayer = Vector3.Distance(Player.position, Enemy.transform.position); if (EnemyDamageZone.GetComponent <EnemyDamage>().HasDied == true) { ChaseMusic.gameObject.SetActive(false); } if (distanceToPlayer < MaxRange) { if (isChecking == true) { isChecking = false; // blocked = NavMesh.Raycast(transform.position, Player.position, out Hit, NavMesh.AllAreas); if (blocked == false) { //Debug.Log("I can see you, you may want to run"); runToPlayer = true; FailedChecks = 0; } if (blocked == true) { // Debug.Log("Missed it by that much"); runToPlayer = false; _animator.SetInteger("State", 1); FailedChecks++; } StartCoroutine(TimedCheck()); } if (runToPlayer == true) { Enemy.GetComponent <EnemyMovement>().enabled = false; if (EnemyDamageZone.GetComponent <EnemyDamage>().HasDied == false) { ChaseMusic.gameObject.SetActive(true); } if (distanceToPlayer > AttackDistance) { _navMeshAgent.isStopped = false; _animator.SetInteger("State", 2); _navMeshAgent.acceleration = 24; _navMeshAgent.SetDestination(Player.position); _navMeshAgent.speed = chaseSpeed; HurtUI.gameObject.SetActive(false); } if (distanceToPlayer < AttackDistance - 0.5f) { _navMeshAgent.isStopped = true; // Debug.Log("Finish him!"); _animator.SetInteger("State", 3); _navMeshAgent.acceleration = 180; HurtUI.gameObject.SetActive(true); Vector3 Position = (Player.position - Enemy.transform.position).normalized; Quaternion PostionRotation = Quaternion.LookRotation(new Vector3(Position.x, 0, Position.z)); Enemy.transform.rotation = Quaternion.Slerp(Enemy.transform.rotation, PostionRotation, Time.deltaTime); } } else if (runToPlayer == false) { _navMeshAgent.isStopped = true; } } }
void Update() { if (Application.isMobilePlatform) { if (Input.touchCount == 1) { Touch touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) { // TODO: Yes I literally reused the code that I could've probably written IFs for... but whatever y'know... Ray ray = Camera.main.ScreenPointToRay(touch.position); RaycastHit rayHit; if (Physics.Raycast(ray, out rayHit)) { // This checks to make sure that we can ONLY click on the pathable ground if (rayHit.transform.tag == "Ground" || rayHit.transform.tag == "Door") { GetComponent <NavMeshAgent>().SetDestination(rayHit.point); // Here we create an array of all Objs that are Clones of Sweets by checking for Tags GameObject[] items = GameObject.FindGameObjectsWithTag("Sweets"); // This checks to make sure that if we have only 1 Sweets Nav Sprite at a time by deleting the rest if (items.Length != 0) { foreach (GameObject _ in items) { Destroy(_); } } Instantiate(nav_sprite, new Vector3(rayHit.point.x, (rayHit.point.y + 0.1f), rayHit.point.z), Quaternion.Euler(new Vector3(90, 0, 0))); } else { NavMeshHit smash; if (NavMesh.SamplePosition(rayHit.point, out smash, 5.0f, NavMesh.AllAreas)) { GetComponent <NavMeshAgent>().SetDestination(rayHit.point); GameObject[] __ = GameObject.FindGameObjectsWithTag("Sweets"); if (__.Length != 0) { foreach (GameObject _ in __) { Destroy(_); } } Instantiate(nav_sprite, new Vector3(smash.position.x, (smash.position.y + 0.1f), smash.position.z), Quaternion.Euler(new Vector3(90, 0, 0))); } } } } } } else { // On RMB Click, Check if the point is a valid move, if yes then go there. if (Input.GetMouseButtonDown(1) || Input.GetMouseButton(1)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit rayHit; if (Physics.Raycast(ray, out rayHit)) { // This checks to make sure that we can ONLY click on the pathable ground if (rayHit.transform.tag == "Ground" || rayHit.transform.tag == "Door") { GetComponent <NavMeshAgent>().SetDestination(rayHit.point); // Debug.Log("This is on Mouse Hit: " + rayHit.point); // Here we create an array of all Objs that are Clones of Sweets by checking for Tags GameObject[] items = GameObject.FindGameObjectsWithTag("Sweets"); // This checks to make sure that if we have only 1 Sweets Nav Sprite at a time by deleting the rest if (items.Length != 0) { foreach (GameObject _ in items) { Destroy(_); } } Instantiate(nav_sprite, new Vector3(rayHit.point.x, (rayHit.point.y + 0.1f), rayHit.point.z), Quaternion.Euler(new Vector3(90, 0, 0))); } else { NavMeshHit smash; if (NavMesh.SamplePosition(rayHit.point, out smash, 5.0f, NavMesh.AllAreas)) { GetComponent <NavMeshAgent>().SetDestination(rayHit.point); // Debug.Log("This is a point: " + smash.position); GameObject[] __ = GameObject.FindGameObjectsWithTag("Sweets"); if (__.Length != 0) { foreach (GameObject _ in __) { Destroy(_); } } Instantiate(nav_sprite, new Vector3(smash.position.x, (smash.position.y + 0.1f), smash.position.z), Quaternion.Euler(new Vector3(90, 0, 0))); } } } } } }
public void Cavar() { if (bocadillos.hormigaSeleccionada != null && bocadillos.hormigaSeleccionada == this) { if (!this.agente.isOnOffMeshLink) { bocadillos.Cavar(); } else { bocadillos.Nada(); } } //esta fuera if (zonaDondeEsta != 0) { Vector3 randomDirection; NavMeshHit aux; bool aux2; do { randomDirection = UnityEngine.Random.insideUnitSphere * 10 + reina.hormiguero.centro; aux2 = NavMesh.SamplePosition(randomDirection, out aux, 1.0f, NavMesh.AllAreas); } while (!aux2); posCavar = new Vector3(aux.position.x, 0, aux.position.z); //Debug.Log("Posicion a la que va: " + siguientePosicionExplorar); agente.SetDestination(posCavar); } else { posCavar = Vector3.zero; if (tiempoQueLlevaHaciendoElTunel < tiempoParaHacerTunel) { tiempoQueLlevaHaciendoElTunel += Time.deltaTime; agente.SetDestination(reina.hormiguero.gameObject.transform.position + new Vector3(Random.Range(0, reina.hormiguero.width), 0, Random.Range(0, reina.hormiguero.heigth))); Task.current.Succeed(); return; } else { int min = -1; int capacidadRestanteHormigas = reina.capacidadTotalDeHormigas - reina.totalHormigas; int capacidadRestanteComida = reina.capacidadTotalDeComida - reina.comidaTotal.Count; int capacidadRestanteHuevos = reina.capacidadTotalDeHuevos - reina.huevosTotal.Count; if (reina.hayQueCrearSalasComida && reina.hayQueCrearSalasHuevos && reina.hayQueCrearSalasHormigas) { min = Reina.CompareLess3(capacidadRestanteHormigas, capacidadRestanteComida, capacidadRestanteHuevos, reina.importanciaHormigas, reina.importanciaComida, reina.importanciaHuevos); } else if (reina.hayQueCrearSalasHormigas && reina.hayQueCrearSalasHuevos) { min = Reina.CompareLess3(capacidadRestanteHormigas, capacidadRestanteComida, capacidadRestanteHuevos, reina.importanciaHormigas, reina.importanciaComida, 0); } else if (reina.hayQueCrearSalasHormigas && reina.hayQueCrearSalasComida) { min = Reina.CompareLess3(capacidadRestanteHormigas, capacidadRestanteComida, capacidadRestanteHuevos, reina.importanciaHormigas, 0, reina.importanciaHuevos); } else if (reina.hayQueCrearSalasComida && reina.hayQueCrearSalasHuevos) { min = Reina.CompareLess3(capacidadRestanteHormigas, capacidadRestanteComida, capacidadRestanteHuevos, 0, reina.importanciaComida, reina.importanciaHuevos); } else if (reina.hayQueCrearSalasHormigas) { min = 0; } else if (reina.hayQueCrearSalasComida) { min = 1; } else if (reina.hayQueCrearSalasHuevos) { min = 2; } Room aux; switch (min) { // no es necesario crear ninguna Sala; case -1: Task.current.Fail(); break; case 0: aux = reina.hormiguero.createCorridor(Room.roomType.LIVEROOM); if (aux != null) { reina.capacidadTotalDeHormigas += aux.capacidadTotalRoom; reina.salasHormigas.Add(aux); reina.hayQueCrearSalasHormigas = false; //Debug.Log("Sala de Hormigas creada, la capacidad ahora es: " + capacidadTotalDeHormigas); tiempoQueLlevaHaciendoElTunel = 0; hayOrdenDeCavar = false; SacarDeOcupadas(); reina.numHormigasCavandoTuneles--; Task.current.Succeed(); } else { reina.espacioLlenoHormiguero = true; tiempoQueLlevaHaciendoElTunel = 0; hayOrdenDeCavar = false; SacarDeOcupadas(); reina.numHormigasCavandoTuneles--; Task.current.Fail(); } break; case 1: aux = reina.hormiguero.createCorridor(Room.roomType.STORAGE); if (aux != null) { reina.salasComida.Add(aux); reina.capacidadTotalDeComida += aux.capacidadTotalRoom; reina.hayQueCrearSalasComida = false; //Debug.Log("Sala de Comida creada, la capacidad ahora es: " + capacidadTotalDeComida); tiempoQueLlevaHaciendoElTunel = 0; hayOrdenDeCavar = false; SacarDeOcupadas(); reina.numHormigasCavandoTuneles--; Task.current.Succeed(); } else { reina.espacioLlenoHormiguero = true; tiempoQueLlevaHaciendoElTunel = 0; hayOrdenDeCavar = false; SacarDeOcupadas(); reina.numHormigasCavandoTuneles--; Task.current.Fail(); } break; case 2: aux = reina.hormiguero.createCorridor(Room.roomType.EGGROOM); if (aux != null) { reina.salasHuevos.Add(aux); reina.capacidadTotalDeHuevos += aux.capacidadTotalRoom; reina.hayQueCrearSalasHuevos = false; //Debug.Log("Sala de Huevos creada, la capacidad ahora es: " + capacidadTotalDeHuevos); tiempoQueLlevaHaciendoElTunel = 0; hayOrdenDeCavar = false; SacarDeOcupadas(); reina.numHormigasCavandoTuneles--; Task.current.Succeed(); } else { reina.espacioLlenoHormiguero = true; tiempoQueLlevaHaciendoElTunel = 0; hayOrdenDeCavar = false; SacarDeOcupadas(); reina.numHormigasCavandoTuneles--; Task.current.Fail(); } break; } } } }
static int _CreateNavMesh(IntPtr L) { int count = LuaDLL.lua_gettop(L); if (count == 0) { NavMesh obj = new NavMesh(); LuaScriptMgr.PushObject(L, obj); return 1; } else { LuaDLL.luaL_error(L, "invalid arguments to method: NavMesh.New"); } return 0; }
public Pather(string continent) { Continent = continent; DetourMesh = new NavMesh(continent, true); }
private void OnGameObjectCreate(GameObject sender, EventArgs args) { try { var missile = sender as MissileClient; if (missile != null && missile.IsValid) { if (missile.SpellCaster != null && !missile.SpellCaster.IsAlly && missile.SData != null) { if (missile.SData.Name.Equals("itemplacementmissile", StringComparison.OrdinalIgnoreCase) && !missile.SpellCaster.IsVisible) { var sPos = missile.StartPosition; var ePos = missile.EndPosition; LeagueSharp.Common.Utility.DelayAction.Add( 1000, delegate { if ( !_wardObjects.Any( w => w.Position.To2D().Distance(sPos.To2D(), ePos.To2D(), false) < 300 && ((int)Game.Time - w.StartT < 2))) { var wObj = new WardObject( GetWardStructForInvisible(sPos, ePos), new Vector3(ePos.X, ePos.Y, NavMesh.GetHeightForPosition(ePos.X, ePos.Y)), (int)Game.Time, null, true, new Vector3(sPos.X, sPos.Y, NavMesh.GetHeightForPosition(sPos.X, sPos.Y))); CheckDuplicateWards(wObj); _wardObjects.Add(wObj); } }); } } } else { var wardObject = sender as Obj_AI_Base; if (wardObject != null && wardObject.IsValid && !wardObject.IsAlly) { foreach (var ward in _wardStructs) { if (wardObject.CharData.BaseSkinName.Equals( ward.ObjectBaseSkinName, StringComparison.OrdinalIgnoreCase)) { _wardObjects.RemoveAll( w => w.Position.Distance(wardObject.Position) < 300 && ((int)Game.Time - w.StartT < 0.5)); var wObj = new WardObject( ward, new Vector3(wardObject.Position.X, wardObject.Position.Y, wardObject.Position.Z), (int)(Game.Time - (int)(wardObject.MaxMana - wardObject.Mana)), wardObject); CheckDuplicateWards(wObj); _wardObjects.Add(wObj); } } } } } catch (Exception ex) { //Global.Logger.AddItem(new LogItem(ex)); } }
public float distanceForMeleeAttack; //the distance for melee attack //this gets all the vairables to correct values public void GetVariablesFromAI() { //to avoid complicating stuff in the prefab #if UNITY_EDITOR if(PrefabUtility.GetPrefabType(gameObject) == PrefabType.Prefab) { return; } #endif if(gameObject.activeSelf == true) { //main objects that are crucial for the ai brain to function patrolManager = GetComponent<AIStateManager>().patrolManager; //the patrol manager sensorParent = GetComponent<AIStateManager>().ears.transform.parent.gameObject; //the parent that holds the sensors ears = GetComponent<AIStateManager>().ears; //the ears object sight = GetComponent<AIStateManager>().sight; //the sight object model = GetComponent<AIStateManager>().animationManager; //data about self, eg height, health eyeHeight = GetComponent<SearchCover>().eyePosition; //the height of the eyes health = GetComponent<AIStateManager>().healthManager.GetComponent<HealthManager>().health; //the amount of health the ai has at the start disengagingHitsToKnockout = GetComponentInChildren<AIHealthExecuter>().disengagingHitsToKnockout; //the amount of disengaging hits the ai can take until it gets disengaged if(GetComponent<NavMeshAgent>() != null) { radius = GetComponent<NavMeshAgent>().radius; //the size of our radius for the navmesh agent height = GetComponent<NavMeshAgent>().height; //our height, for the nav mesh agent } //data about enemies, such as height, tag etc.. tagOfEnemy = GetComponent<AIStateManager>().tagToAvoidPrimary; //the tag of the enemy tagOfBullet = GetComponent<AIStateManager>().tagToAvoidSecondary; //the tag of the object that shows danger, eg bullets enemyCriticalHeight = GetComponent<AIStateManager>().enemyHeight; //the height at which the ai should aim initAmmo = GetComponent<AIWeaponController>().amountOfAmmo; //the amount of ammo at the start //reaction times, how quick does the ai react etc... shockTime = GetComponent<AIStateManager>().shockTime; //seconds, how quickly we react to seeing an enemy, reference and manipulated by anderenaline freezeTime = GetComponent<AIStateManager>().freezeTime; //seconds, how long we freeze when we hear a bullet minCoverTime = GetComponent<AIStateManager>().minCoverTime; //seconds, minimum amount of time to hide in cover maxCoverTime = GetComponent<AIStateManager>().maxCoverTime; //seconds, maximum amount of time to hide in cover timeBetweenEnemyChecks = GetComponent<AIStateManager>().timeUntilNextCheck; //seconds, amount of time when we check whether the others are a danger or not timeForGivingUpDuringEngagement = GetComponent<AIStateManager>().investigationTime; //seconds, the amount of time the ai will try and locate the enemy during an engagment before giving up and going back to patrol timeForGivingUpSeeking = GetComponent<AIStateManager>().timeBarrierEngageToInvestigate; //frames, the amount of time the ai will try and locate the enemy if we suddenly see somebody else before giving up and going back to patrol //emotion control initAndrenaline = GetComponent<AIStateManager>().andrenaline; //the amount of andrenaline we start off with initFear = GetComponent<AIStateManager>().fear; //the amount of fear the ai starts off with chanceForFight = GetComponent<AIStateManager>().chanceForFight; //the percentage for fight or flight instict, reference manipulated by andrenaline //weapons and engagement weapon = GetComponent<AIWeaponController>().weaponHoldingObject; //the weapon object otherWeapons = GetComponent<AIStateManager>().otherWeapons; //other weapons otherWeaponsMelee = GetComponent<AIStateManager>().otherWeaponsMelee; //other weapons melee weaponHoldingLocation = GetComponent<AIWeaponController>().weaponHoldingLocation; //the object where the weapon is held targetCheck = GetComponent<AIStateManager>().targetVisualCheck; //the name of the script that return whether the ai should attack or not targetVisualCheckChance = GetComponent<AIStateManager>().targetVisualCheckChance; distanceToEngageCloseCombatLogic = GetComponent<AIStateManager>().distanceToStopWalking; //the distance at which to engage offsetFactor = GetComponent<AIStateManager>().offsetFactor; //speed references refSpeedPatrol = GetComponent<AIStateManager>().maxSpeedPatrol; //the reference speed for the patrol refSpeedEngage = GetComponent<AIStateManager>().maxSpeedEngage; //the reference speed for when the ai engages refSpeedChase = GetComponent<AIStateManager>().maxSpeedChase; //the reference speed for chase refSpeedCover = GetComponent<AIStateManager>().maxSpeedCover; //the refernce speed at which the ai runs to cover //model stuff modelParentOfAllBones = model.GetComponent<RagdollTransitions>().boneParent; //the parent object that takes in all bones handToUseInCharacter = model.GetComponent<HandIK>().handToUseInCharacter; //patrol sutff if(patrolManager.GetComponent<PatrolManager>() != null) { waypointList = patrolManager.GetComponent<PatrolManager>().waypointList; //the list that contains all waypoinjts in correct order distanceToWaypointForRegistering = patrolManager.GetComponent<PatrolManager>().criticalDistanceToWaypoint; //how far we have to be from the waypoint for it to register that we are at it navmeshToUse = patrolManager.GetComponent<PatrolManager>().meshNav; //the navmesh to use } if(GetComponent<AIMovementController>() != null) { patrolMinDistanceToDestination = GetComponent<AIMovementController>().minDistanceToDestination; patrolFramesCriticalCheck = GetComponent<AIMovementController>().framesCriticalCheck; patrolChecksCritical = GetComponent<AIMovementController>().checksCriticalUntilStop; } if(GetComponent<AIMovementControllerASTAR>() != null) { patrolMinDistanceToDestination = GetComponent<AIMovementControllerASTAR>().minDistanceToDestination; patrolFramesCriticalCheck = GetComponent<AIMovementControllerASTAR>().framesCriticalCheck; patrolChecksCritical = GetComponent<AIMovementControllerASTAR>().checksCriticalUntilStop; } //optimisation stuff coverAmountOfRays = GetComponent<SearchCover>().amountOfRays; //the amount of rays that should be used to sample cover (the more the better, more slower) coverFieldOfView = GetComponent<SearchCover>().fieldOfRays; //the field of view from which we find cove (recommend 360 for most cases) coverDistanceToCheck = GetComponent<SearchCover>().distanceToCheck; //how far should the rays shoot; usually some arbitary large number patrolTickBarrier = GetComponent<AIStateManager>().tickBarrier; //this is how often the ai brain should check the patroling coverTrueCoverTest = GetComponent<SearchCover>().trueCoverTest; //melee stuff meleeSetting = GetComponent<AIStateManager>().meleeAttackUsed; distanceForMeleeAttack = GetComponent<AIStateManager>().meleeAttackDistance; } }
public void RemoveAllNavMeshLoadedData() { NavMesh.RemoveAllNavMeshData(); }
/// <summary> /// Returns true if the position is a valid pathfinding position. /// </summary> /// <param name="position">The position to sample.</param> /// <returns>True if the position is a valid pathfinding position.</returns> protected bool SamplePosition(Vector3 position) { NavMeshHit hit; return(NavMesh.SamplePosition(position, out hit, navMeshAgent.height * 2, NavMesh.AllAreas)); }
new protected void Start() { base.Start(); // DesPos = transform.position; NavMsh = FindObjectOfType<NavMesh>(); TargetNode = CurNode = NavMsh.findNode(Trnsfrm.position); // Rpc_DesPos(Body.position); //WRONG!! }
void SetNavMesh(NavMesh navMesh) { this.navMesh = navMesh; }
void GetVariablesFromChild() { childScript.GetVariablesFromAI(); //main objects that are crucial for the ai brain to function patrolManager = childScript.patrolManager; //the patrol manager sensorParent = childScript.sensorParent; //the parent that holds the sensors ears = childScript.ears; //the ears object sight = childScript.sight; //the sight object model = childScript.model; //the object that holds the model //data about self, eg height, health eyeHeight = childScript.eyeHeight; //the height of the eyes health = childScript.health; //the amount of health the ai has at the start disengagingHitsToKnockout = childScript.disengagingHitsToKnockout; //the amount of disengaging hits the ai can take until it gets disengaged radius = childScript.radius; //the size of our radius for the navmesh agent height = childScript.height; //our height, for the nav mesh agent //data about enemies, such as height, tag etc.. tagOfEnemy = childScript.tagOfEnemy; //the tag of the enemy tagOfBullet = childScript.tagOfBullet; //the tag of the object that shows danger, eg bullets enemyCriticalHeight = childScript.enemyCriticalHeight; //the height at which the ai should aim initAmmo = childScript.initAmmo; //the amount of ammo at the start //reaction times, how quick does the ai react etc... shockTime = childScript.shockTime; //seconds, how quickly we react to seeing an enemy, reference and manipulated by anderenaline freezeTime = childScript.freezeTime; //seconds, how long we freeze when we hear a bullet minCoverTime = childScript.minCoverTime; //seconds, minimum amount of time to hide in cover maxCoverTime = childScript.maxCoverTime; //seconds, maximum amount of time to hide in cover timeBetweenEnemyChecks = childScript.timeBetweenEnemyChecks; //seconds, amount of time when we check whether the others are a danger or not timeForGivingUpDuringEngagement = childScript.timeForGivingUpDuringEngagement; //seconds, the amount of time the ai will try and locate the enemy during an engagment before giving up and going back to patrol timeForGivingUpSeeking = childScript.timeForGivingUpSeeking; //frames, the amount of time the ai will try and locate the enemy if we suddenly see somebody else before giving up and going back to patrol //emotion control initAndrenaline = childScript.initAndrenaline; //the amount of andrenaline we start off with initFear = childScript.initFear; //the amount of fear the ai starts off with chanceForFight = childScript.chanceForFight; //the percentage for fight or flight instict, reference manipulated by andrenaline //weapons and engagement weapon = childScript.weapon; //the weapon object weaponHoldingLocation = childScript.weaponHoldingLocation; //the object where the weapon is held otherWeapons = childScript.otherWeapons; otherWeaponsMelee = childScript.otherWeaponsMelee; targetCheck = childScript.targetCheck; //the name of the script that return whether the ai should attack or not targetVisualCheckChance = childScript.targetVisualCheckChance; distanceToEngageCloseCombatLogic = childScript.distanceToEngageCloseCombatLogic; //the distance at which to engage offsetFactor = childScript.offsetFactor; //speed references refSpeedPatrol = childScript.refSpeedPatrol; //the reference speed for the patrol refSpeedEngage = childScript.refSpeedEngage; //the reference speed for when the ai engages refSpeedChase = childScript.refSpeedChase; //the reference speed for chase refSpeedCover = childScript.refSpeedCover; //the refernce speed at which the ai runs to cover //model stuff modelParentOfAllBones = childScript.modelParentOfAllBones; //the parent object that takes in all bones handToUseInCharacter = childScript.handToUseInCharacter; //patrol sutff waypointList = childScript.waypointList; //the list that contains all waypoinjts in correct order distanceToWaypointForRegistering = childScript.distanceToWaypointForRegistering; //how far we have to be from the waypoint for it to register that we are at it navmeshToUse = childScript.navmeshToUse; //the navmesh to use patrolMinDistanceToDestination = childScript.patrolMinDistanceToDestination; patrolFramesCriticalCheck = childScript.patrolFramesCriticalCheck; patrolChecksCritical = childScript.patrolChecksCritical; //optimisation stuff coverAmountOfRays = childScript.coverAmountOfRays; //the amount of rays that should be used to sample cover (the more the better, more slower) coverFieldOfView = childScript.coverFieldOfView; //the field of view from which we find cove (recommend 360 for most cases) coverDistanceToCheck = childScript.coverDistanceToCheck; //how far should the rays shoot; usually some arbitary large number patrolTickBarrier = childScript.patrolTickBarrier; //this is how often the ai brain should check the patroling coverTrueCoverTest = childScript.coverTrueCoverTest; //melee stuff meleeSetting = childScript.meleeSetting; distanceForMeleeAttack = childScript.distanceForMeleeAttack; }
public void Generate() { var navMesh = new NavMesh(this.game); var intersectionMap = new Dictionary<Intersection, MergedIntersection>(); var intersectionSideMap = new Dictionary<MergedIntersection, Game.Street[]>(); var intersectionQuadMap = new Dictionary<MergedIntersection, NavQuad>(); foreach (var mergedIntersection in this.game.GetList<MergedIntersection>()) { var streets = new Game.Street[4]; foreach (var street in mergedIntersection.Streets) { var thisNode = mergedIntersection .Intersections.First(i => i == street.Node1 || i == street.Node2); var otherNode = street.OtherNode(thisNode); var diff = otherNode.Position - thisNode.Position; if (diff.X == 0.U()) { streets[diff.Y > 0.U() ? Block.Side.North : Block.Side.South] = street; } else if (diff.Y == 0.U()) { streets[diff.X > 0.U() ? Block.Side.East : Block.Side.West] = street; } else { throw new Exception(""); } } var padding = 0.3.U(); var cornerSW = getIntersectionCorner(streets, Block.Corner.SouthWest); var cornerSE = getIntersectionCorner(streets, Block.Corner.SouthEast); var cornerNW = getIntersectionCorner(streets, Block.Corner.NorthWest); var cornerNE = getIntersectionCorner(streets, Block.Corner.NorthEast); var navQuad = new NavQuad( cornerSW + new Difference2(padding, padding), cornerSE + new Difference2(-padding, padding), cornerNW + new Difference2(padding, -padding), cornerNE + new Difference2(-padding, -padding) ); navMesh.Add(navQuad); intersectionSideMap.Add(mergedIntersection, streets); intersectionQuadMap.Add(mergedIntersection, navQuad); foreach (var intersection in mergedIntersection.Intersections) { intersectionMap.Add(intersection, mergedIntersection); } } foreach (var mergedIntersection in this.game.GetList<MergedIntersection>()) { var intersectionQuad = intersectionQuadMap[mergedIntersection]; foreach (var street in mergedIntersection.Streets .Where(s => mergedIntersection.Intersections.Contains(s.Node1))) { var side = (Block.Side)Array.IndexOf(intersectionSideMap[mergedIntersection], street); var quad1 = intersectionQuad; var quad2 = intersectionQuadMap[intersectionMap[street.Node2]]; if (side == Block.Side.East || side == Block.Side.West) { if (side == Block.Side.East) { Do.Swap(ref quad1, ref quad2); } var navQuad = new NavQuad(quad2.SE, quad1.SW, quad2.NE, quad1.NW); NavLink.CreatePair(navQuad, quad1, quad1.SW, quad1.NW); NavLink.CreatePair(navQuad, quad2, quad2.SE, quad2.NE); navMesh.Add(navQuad); } else if (side == Block.Side.South || side == Block.Side.North) { if (side == Block.Side.South) { Do.Swap(ref quad1, ref quad2); } var navQuad = new NavQuad(quad1.NW, quad1.NE, quad2.SW, quad2.SE); NavLink.CreatePair(navQuad, quad1, quad1.NW, quad1.NE); NavLink.CreatePair(navQuad, quad2, quad2.SW, quad2.SE); navMesh.Add(navQuad); } } } }
bool fixNodeI( ref int cni, NavMesh.Node n ) { for(int i = cni; i-- > 0; ) { if(Path.Smooth[i].N == n) { //Debug.Log("fwd " + i + " old -| " + cni); cni = i; // goto label_CurNodeResolved; //resloved - we are following path properly return true; } } for(int i = cni; ++i < Path.Smooth.Count; ) { if(Path.Smooth[i].N == n) { // Debug.Log("rewind " + i + " old -| " + cni); cni = i; return true; // goto label_CurNodeResolved; //resloved - we have somhw been bumped back... no matter rewind a bit... (also rewind smoother) } } return false; }
public bool Walkable(NavMesh navigation) { return(this.navigation == navigation && navigation != null && navigation.GetFaceWalkable(face)); }
public void TestNavMesh(byte[] data) { var extents = new Vector3(2.5f, 2.5f, 2.5f).ToFloatArray(); // var startVec = new Vector3(-9467.8f, 64.2f, 55.9f); //var endVec = new Vector3(-9248.9f, -93.35f, 70.3f); //Vector3 startVec = new Vector3(1672.2f, 1662.9f, 139.2f); //Vector3 startVec = new Vector3(1665.2f, 1678.2f, 120.5f); Vector3 startVec = new Vector3 ( -8949.95f, -132.493f, 83.5312f ); Vector3 endVec = new Vector3 ( -9046.507f, -45.71962f, 88.33186f ); var start = startVec.ToRecast().ToFloatArray(); var end = endVec.ToRecast().ToFloatArray(); NavMesh _mesh = new NavMesh(); _mesh.Initialize(32768, 4096, Helpers.Origin, Helpers.TileSize, Helpers.TileSize); var meshData = data; MeshTile tile; _mesh.AddTile(data, out tile); NavMeshQuery _query = new NavMeshQuery(); _query.Initialize(_mesh, 65536); QueryFilter Filter = new QueryFilter { IncludeFlags = 0xFFFF, ExcludeFlags = 0x0 }; var startRef = _query.FindNearestPolygon(start, extents, Filter); var endRef = _query.FindNearestPolygon(end, extents, Filter); uint[] pathCorridor; var status = _query.FindPath(startRef, endRef, start, end, Filter, out pathCorridor); if (status.Equals(DetourStatus.Failure) || pathCorridor == null) throw new Exception("FindPath failed, start: " + startRef + " end: " + endRef); if (status.HasFlag(DetourStatus.PartialResult)) Console.WriteLine("Warning, partial result: " + status); float[] finalPath; StraightPathFlag[] pathFlags; uint[] pathRefs; status = _query.FindStraightPath(start, end, pathCorridor, out finalPath, out pathFlags, out pathRefs); if (status.Equals(DetourStatus.Failure) || (finalPath == null || pathFlags == null || pathRefs == null)) throw new Exception("FindStraightPath failed, refs in corridor: " + pathCorridor.Length); }
public static bool IsWall(Vector3 position) { var cFlags = NavMesh.GetCollisionFlags(position); return(cFlags == CollisionFlags.Wall || cFlags == CollisionFlags.Building || cFlags == CollisionFlags.Prop); }
private IList<Point> GetPoints(string filename, NavMesh.Vector start, NavMesh.Vector end) { return Mesh.FindPath(filename, start, end).Select(vector => new Point(vector.X, vector.Y)).ToList(); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Please supply continent name"); return; } var continent = args[0]; var path = "S:\\meshReader\\Meshes\\" + continent; if (!Directory.Exists(path)) { Console.WriteLine("Can't find mesh directory: " + path); return; } Console.Write("Setting up data storage.. "); string floodDir = "S:\\meshReader\\Meshes\\Floodfill\\"; if (!Directory.Exists(floodDir)) Directory.CreateDirectory(floodDir); floodDir += continent; if (Directory.Exists(floodDir)) Directory.Delete(floodDir, true); Directory.CreateDirectory(floodDir); floodDir += "\\"; Console.WriteLine("done"); var files = Directory.GetFiles(path).Where(f => f.EndsWith(".tile")); Console.WriteLine("Total amount of tiles: " + files.Count()); if (files.Count() > 4096) { Console.WriteLine("Too many tiles. Increase maxTiles."); return; } Console.WriteLine("Initializing mesh.."); var mesh = new NavMesh(); if ((mesh.Initialize(32768, 4096, Utility.Origin, Utility.TileSize, Utility.TileSize) & DetourStatus.Failure) != 0) { Console.WriteLine("Failed to initialize mesh."); return; } Console.WriteLine("Loading all tiles.."); var tiles = new List<MeshTile>(files.Count()); foreach (var file in files) { var data = File.ReadAllBytes(file); MeshTile tile; if ((mesh.AddTile(data, out tile) & DetourStatus.Failure) != 0) { Console.WriteLine("Failed to load tile: " + file); return; } tiles.Add(tile); } Console.WriteLine("Initializing DBC backend..."); MpqManager.InitializeDBC("S:\\WoW"); Console.Write("Identifiying map id.. "); int mapId = PhaseHelper.GetMapIdByName(continent); if (mapId < 0) { Console.WriteLine("failed"); return; } Console.WriteLine(mapId); Console.Write("Identifying source points.. "); var sourcePoints = new List<Vector3>(100); sourcePoints.AddRange(from record in TaxiHelper.TaxiNodesDBC.Records select new TaxiNode(record) into node where node.IsValid && node.MapId == mapId select node.Location.ToRecast()); Console.WriteLine(sourcePoints.Count); Console.WriteLine("Initializing flood fill.."); var floodFill = new FloodFill(mesh); Console.WriteLine("Flooding.. "); foreach (var source in sourcePoints) floodFill.ExecuteFrom(source); Console.WriteLine("Finished, visited " + floodFill.Marked + " polygons"); Console.WriteLine("Rebuilding tiles..."); var config = RecastConfig.Default; long sizeBefore = 0; long sizeAfter = 0; foreach (var tile in tiles) { sizeBefore += tile.DataSize; byte[] rebuiltData; if (!tile.Rebuild(floodFill.Visited, floodFill.VisitedMask, config.CellHeight, config.MaxVertsPerPoly, out rebuiltData)) { Console.WriteLine("Failed to rebuild tile " + tile.Header.X + " " + tile.Header.Y); continue; } if (rebuiltData == null) { Console.WriteLine("Tile " + tile.Header.X + " " + tile.Header.Y + " ceases to exist."); continue; } sizeAfter += rebuiltData.Length; File.WriteAllBytes(floodDir + continent + "_" + tile.Header.X + "_" + tile.Header.Y + ".tile", rebuiltData); } Console.WriteLine("All done, size before: " + (sizeBefore / 1024 / 1024) + "MiB after: " + (sizeAfter / 1024 / 1024) + "MiB"); Console.ReadKey(true); }
// Update is called once per frame void Update() { // Getting positions positionPNJ = agent.transform.position; player1Position = player1.transform.position; player2Position = player2.transform.position; player3Position = player3.transform.position; // timer to prevent pnj from being stuck to each others (ish) if (rb.velocity.magnitude < 0.1f) { if (targetTime <= 0) { float random = Random.Range(0, 10); if (agent.transform.position.x < 0) // Gauche { if (random < 4) { agent.SetDestination(getPointRandomValide(-20f, 0f, 4f, 17f)); targetTime = 1f; return; } else { agent.SetDestination(getPointRandomValide(-20f, -1f, -10f, 3f)); targetTime = 1f; return; } } else // Droite { if (random < 4) { agent.SetDestination(getPointRandomValide(3f, 20f, 4f, 17f)); targetTime = 1f; return; } else { agent.SetDestination(getPointRandomValide(3f, 20f, -10f, 3f)); targetTime = 1f; return; } } } targetTime -= Time.deltaTime; } else { targetTime = 1f; } // Verifying security distance from players float distanceJoueur1 = Vector3.Distance(player1Position, positionPNJ); float distanceJoueur2 = Vector3.Distance(player2Position, positionPNJ); float distanceJoueur3 = Vector3.Distance(player3Position, positionPNJ); if (distanceJoueur1 < 2 || distanceJoueur2 < 2 || distanceJoueur3 < 2) { if (distanceJoueur1 < 2) { float x = player1Position.x + (positionPNJ.x - player1Position.x) * 2; float z = player1Position.z + (positionPNJ.z - player1Position.z) * 2; positionDestination = new Vector3(x, 1, z); } if (distanceJoueur2 < 2) { float x = player2Position.x + (positionPNJ.x - player2Position.x) * 2; float z = player2Position.z + (positionPNJ.z - player2Position.z) * 2; positionDestination = new Vector3(x, 1, z); } if (distanceJoueur3 < 2) { float x = player3Position.x + (positionPNJ.x - player3Position.x) * 2; float z = player3Position.z + (positionPNJ.z - player3Position.z) * 2; positionDestination = new Vector3(x, 1, z); } // Si il est impossible d'éviter l'eventuel conflit du point de destination NavMeshHit hit2; if (!NavMesh.SamplePosition(positionDestination, out hit2, 1.0f, NavMesh.AllAreas)) { positionDestination = getPointRandomValide(-20f, 20f, -10f, 17f); } else { // évite l'éventuel conflit (ne fait rien si pas de confilt) NavMesh.SamplePosition(positionDestination, out hit2, 1.0f, NavMesh.AllAreas); positionDestination = hit2.position; } } //Debug.Log("Distance :" + Vector3.Distance(positionDestination, positionPNJ)); if (Vector3.Distance(positionDestination, positionPNJ) < 2) { positionDestination = getPointRandomValide(-20f, 20f, -10f, 17f); } agent.SetDestination(positionDestination); }
bool isWall(Vector3 Pos) { CollisionFlags cFlags = NavMesh.GetCollisionFlags(Pos); return(cFlags == CollisionFlags.Wall); }
// Update is called once per frame void Update() { StartTime = StartTime.AddSeconds(1); status = index + "/" + times.Count + "to " + agent.destination + "/" + positions[index] + "sta: " + agent.pathStatus; if (StartTime < times [0]) { transform.GetComponent <MeshRenderer> ().enabled = false; transform.GetComponent <Collider> ().enabled = false; } else { transform.GetComponent <MeshRenderer> ().enabled = true; transform.GetComponent <Collider> ().enabled = true; } //For time control /* * Actually there are __ status: * 1. position in navmesh and createde destination succussflly --> Success part (calculate speed) * 2. position not in navmesh * 2.1 nopath --> find the closest position * * * */ if ((pathpend && !agent.hasPath) || (pathpend && agent.pathStatus == NavMeshPathStatus.PathPartial)) { pathpend = false; NavMeshHit hit; if (NavMesh.SamplePosition(positions [index], out hit, 500, NavMesh.AllAreas)) { agent.SetDestination(hit.position); NavMeshPath pat = new NavMeshPath(); agent.CalculatePath(agent.destination, pat); agent.speed = CalSpeed(pat); for (int i = 0; i < pat.corners.Length - 1; i++) { Debug.DrawLine(pat.corners [i], pat.corners [i + 1], Color.blue, 1000); } } else { Debug.Log(transform.name + "----------------"); } } // find the closest position if (pathpend && !agent.pathPending && index + 1 <= times.Count) { pathpend = false; NavMeshPath pat = new NavMeshPath(); agent.CalculatePath(agent.destination, pat); agent.speed = CalSpeed(pat); for (int i = 0; i < pat.corners.Length - 1; i++) { Debug.DrawLine(pat.corners [i], pat.corners [i + 1], Color.green, 1000); } } // Success Part if (StartTime >= times [index] && index + 1 < times.Count) { //Tw: GameObject box = Instantiate(TwBox, positions[index], Quaternion.identity); box.name = transform.name + "/ " + index; Debug.Log("now: " + StartTime + " Going to: " + positions [index]); //then move agent.SetDestination(positions [index + 1]); NavMeshPath pat = new NavMeshPath(); agent.CalculatePath(agent.destination, pat); for (int i = 0; i < pat.corners.Length - 1; i++) { Debug.DrawLine(pat.corners [i], pat.corners [i + 1], Color.red, 1000); } pathpend = true; Debug.DrawRay(positions [index], Vector3.up * 600, Color.red, 1000, false); //Debug.Log ("now: " + times [index] + " Going to: " + positions [index]); index++; } else if (index + 1 == times.Count) { transform.GetComponent <MeshRenderer> ().enabled = false; transform.GetComponent <Collider> ().enabled = false; } }
protected void Start() { // Target = FindObjectOfType<PlayerController>(); NavMsh = FindObjectOfType<NavMesh>(); TargetNode = CurNode = NavMsh.findNode(Trnsfrm.position, CurNode); TargetP = ValidPos = Trnsfrm.position; invincibleTimer = invincibleTimerInit; }
// --------------------------------------------------------------- // Name : LateUpdate // Desc : Called by Unity at the end of every frame update. Used // here to perform reanimation. // --------------------------------------------------------------- protected virtual void LateUpdate() { if (_boneControlType == AIBoneControlType.RagdollToAnim) { if (Time.time <= _ragdollEndTime + _mecanimTransitionTime) { Vector3 animatedToRagdoll = _ragdollHipPosition - _rootBone.position; Vector3 newRootPosition = transform.position + animatedToRagdoll; RaycastHit[] hits = Physics.RaycastAll(newRootPosition + (Vector3.up * 0.25f), Vector3.down, float.MaxValue, _geometryLayers); newRootPosition.y = float.MinValue; foreach (RaycastHit hit in hits) { if (!hit.transform.IsChildOf(transform)) { newRootPosition.y = Mathf.Max(hit.point.y, newRootPosition.y); } } NavMeshHit navMeshHit; Vector3 baseOffset = Vector3.zero; if (_navAgent) { baseOffset.y = _navAgent.baseOffset; } if (NavMesh.SamplePosition(newRootPosition, out navMeshHit, 25.0f, NavMesh.AllAreas)) { transform.position = navMeshHit.position + baseOffset; } else { transform.position = newRootPosition + baseOffset; } Vector3 ragdollDirection = _ragdollHeadPosition - _ragdollFeetPosition; ragdollDirection.y = 0.0f; Vector3 meanFeetPosition = 0.5f * (_animator.GetBoneTransform(HumanBodyBones.LeftFoot).position + _animator.GetBoneTransform(HumanBodyBones.RightFoot).position); Vector3 animatedDirection = _animator.GetBoneTransform(HumanBodyBones.Head).position - meanFeetPosition; animatedDirection.y = 0.0f; //Try to match the rotations. Note that we can only rotate around Y axis, as the animated characted must stay upright, //hence setting the y components of the vectors to zero. transform.rotation *= Quaternion.FromToRotation(animatedDirection.normalized, ragdollDirection.normalized); } // Calculate Interpolation value float blendAmount = Mathf.Clamp01((Time.time - _ragdollEndTime - _mecanimTransitionTime) / _reanimationBlendTime); // Calculate blended bone positions by interplating between ragdoll bone snapshots and animated bone positions foreach (BodyPartSnapshot snapshot in _bodyPartSnapShots) { if (snapshot.transform == _rootBone) { snapshot.transform.position = Vector3.Lerp(snapshot.position, snapshot.transform.position, blendAmount); } snapshot.transform.rotation = Quaternion.Slerp(snapshot.rotation, snapshot.transform.rotation, blendAmount); } // Conditional to exit reanimation mode if (blendAmount == 1.0f) { _boneControlType = AIBoneControlType.Animated; if (_navAgent) { _navAgent.enabled = true; } if (_collider) { _collider.enabled = true; } AIState newState = null; if (_states.TryGetValue(AIStateType.Alerted, out newState)) { if (_currentState != null) { _currentState.OnExitState(); } newState.OnEnterState(); _currentState = newState; _currentStateType = AIStateType.Alerted; } } } }
public void Tick(IHTNAgent npc, float deltaTime, float time) { NavMeshHit navMeshHit; ScientistJunkpileContext npcContext = npc.AiDomain.NpcContext as ScientistJunkpileContext; if (npcContext == null || npcContext.Domain.NavAgent == null) { return; } if (npcContext.Location == null || npcContext.Location.PatrolPointGroup == null) { return; } if (this.WaypointSet == null) { this.WaypointSet = npcContext.Location.PatrolPointGroup.GetComponent <Rust.Ai.WaypointSet>(); } if (this.WaypointSet == null || this.WaypointSet.Points.Count == 0) { return; } if (npcContext.IsFact(Facts.IsReturningHome) || npcContext.IsFact(Facts.HasEnemyTarget) || npcContext.IsFact(Facts.NearbyAnimal) || !npcContext.IsFact(Facts.IsUsingTool)) { this.isFollowingWaypoints = false; this.hasAlreadyPassedOnPrevCheck = false; return; } if (!this.isFollowingWaypoints) { if (!this.hasAlreadyPassedOnPrevCheck && (npcContext.GetPreviousFact(Facts.HasEnemyTarget) == 1 || npcContext.GetPreviousFact(Facts.NearbyAnimal) == 1) || this.isFirstTick) { this.CurrentWaypointIndex = this.GetClosestWaypointIndex(npcContext.BodyPosition); if (!this.isFirstTick) { this.hasAlreadyPassedOnPrevCheck = true; } else { this.isFirstTick = false; } } Rust.Ai.WaypointSet.Waypoint item = this.WaypointSet.Points[this.CurrentWaypointIndex]; if (item.Transform == null) { this.CurrentWaypointIndex = this.GetNextWaypointIndex(); this.isFollowingWaypoints = false; return; } Vector3 transform = item.Transform.position; if ((npcContext.Memory.TargetDestination - transform).sqrMagnitude > 0.1f && NavMesh.SamplePosition(transform + (Vector3.up * 2f), out navMeshHit, 4f, npcContext.Domain.NavAgent.areaMask)) { item.Transform.position = navMeshHit.position; npcContext.Domain.SetDestination(navMeshHit.position); this.isFollowingWaypoints = true; npcContext.SetFact(Facts.IsNavigating, true, true, true, true); return; } } float single = 2f; float navAgent = npcContext.Domain.NavAgent.stoppingDistance * npcContext.Domain.NavAgent.stoppingDistance; if ((npcContext.BodyPosition - npcContext.Memory.TargetDestination).sqrMagnitude > navAgent + single) { return; } this.CurrentWaypointIndex = this.GetNextWaypointIndex(); this.isFollowingWaypoints = false; }
/// <summary> /// Gets the SOLO Vayne Q position using a patented logic! /// </summary> /// <returns></returns> public static Vector3 GetSOLOVayneQPosition() { #region The Required Variables var positions = TumbleHelper.GetRotatedQPositions(); var enemyPositions = TumbleHelper.GetEnemyPoints(); var safePositions = positions.Where(pos => !enemyPositions.Contains(pos.To2D())).ToList(); var BestPosition = ObjectManager.Player.ServerPosition.LSExtend(Game.CursorPos, 300f); var AverageDistanceWeight = .60f; var ClosestDistanceWeight = .40f; var bestWeightedAvg = 0f; var highHealthEnemiesNear = HeroManager.Enemies.Where(m => !m.IsMelee && m.IsValidTarget(1300f) && m.HealthPercent > 7).ToList(); var alliesNear = HeroManager.Allies.Count(ally => !ally.IsMe && ally.IsValidTarget(1500f)); var enemiesNear = HeroManager.Enemies.Where(m => m.IsValidTarget(Orbwalking.GetRealAutoAttackRange(m) + 300f + 65f)) .ToList(); #endregion #region 1 Enemy around only if (ObjectManager.Player.CountEnemiesInRange(1500f) <= 1) { //Logic for 1 enemy near var position = ObjectManager.Player.ServerPosition.LSExtend(Game.CursorPos, 300f); return(position); } #endregion if ( enemiesNear.Any( t => t.Health + 15 < ObjectManager.Player.LSGetAutoAttackDamage(t) * 2 + ObjectManager.Player.LSGetSpellDamage(t, SpellSlot.Q) && t.LSDistance(ObjectManager.Player) < Orbwalking.GetRealAutoAttackRange(t) + 80f)) { var QPosition = ObjectManager.Player.ServerPosition.LSExtend( enemiesNear.OrderBy(t => t.Health).First().ServerPosition, 300f); if (!LeagueSharp.Common.Utility.UnderTurret(QPosition, true)) { return(QPosition); } } #region Alone, 2 Enemies, 1 Killable if (enemiesNear.Count() <= 2) { if ( enemiesNear.Any( t => t.Health + 15 < ObjectManager.Player.LSGetAutoAttackDamage(t) * 2 + ObjectManager.Player.LSGetSpellDamage(t, SpellSlot.Q) && t.LSDistance(ObjectManager.Player) < Orbwalking.GetRealAutoAttackRange(t) + 80f)) { var QPosition = ObjectManager.Player.ServerPosition.LSExtend( highHealthEnemiesNear.OrderBy(t => t.Health).First().ServerPosition, 300f); if (!LeagueSharp.Common.Utility.UnderTurret(QPosition, true)) { return(QPosition); } } } #endregion #region Alone, 2 Enemies, None Killable if (alliesNear == 0 && highHealthEnemiesNear.Count() <= 2) { //Logic for 2 enemies Near and alone //If there is a killable enemy among those. var backwardsPosition = (ObjectManager.Player.ServerPosition.To2D() + 300f * ObjectManager.Player.Direction.To2D()).To3D(); if (!LeagueSharp.Common.Utility.UnderTurret(backwardsPosition, true)) { return(backwardsPosition); } } #endregion #region Already in an enemy's attack range. var closeNonMeleeEnemy = TumbleHelper.GetClosestEnemy(ObjectManager.Player.ServerPosition.LSExtend(Game.CursorPos, 300f)); if (closeNonMeleeEnemy != null && ObjectManager.Player.LSDistance(closeNonMeleeEnemy) <= closeNonMeleeEnemy.AttackRange - 85 && !closeNonMeleeEnemy.IsMelee) { return(ObjectManager.Player.ServerPosition.LSExtend(Game.CursorPos, 300f).IsSafeEx() ? ObjectManager.Player.ServerPosition.LSExtend(Game.CursorPos, 300f) : Vector3.Zero); } #endregion #region Logic for multiple enemies / allies around. foreach (var position in safePositions) { var enemy = TumbleHelper.GetClosestEnemy(position); if (!enemy.LSIsValidTarget()) { continue; } var avgDist = TumbleHelper.GetAvgDistance(position); if (avgDist > -1) { var closestDist = ObjectManager.Player.ServerPosition.LSDistance(enemy.ServerPosition); var weightedAvg = closestDist * ClosestDistanceWeight + avgDist * AverageDistanceWeight; if (weightedAvg > bestWeightedAvg && position.IsSafeEx()) { bestWeightedAvg = weightedAvg; BestPosition = position; } } } #endregion var endPosition = BestPosition.IsSafe() ? BestPosition : Game.CursorPos; #region Couldn't find a suitable position, tumble to nearest ally logic if (endPosition == Vector3.Zero) { //Try to find another suitable position. This usually means we are already near too much enemies turrets so just gtfo and tumble //to the closest ally ordered by most health. var alliesClose = HeroManager.Allies.Where(ally => !ally.IsMe && ally.IsValidTarget(1500f)).ToList(); if (alliesClose.Any() && enemiesNear.Any()) { var closestMostHealth = alliesClose.OrderBy(m => m.LSDistance(ObjectManager.Player)) .ThenByDescending(m => m.Health) .FirstOrDefault(); if (closestMostHealth != null && closestMostHealth.LSDistance( enemiesNear.OrderBy(m => m.LSDistance(ObjectManager.Player)).FirstOrDefault()) > ObjectManager.Player.LSDistance( enemiesNear.OrderBy(m => m.LSDistance(ObjectManager.Player)).FirstOrDefault())) { var tempPosition = ObjectManager.Player.ServerPosition.LSExtend(closestMostHealth.ServerPosition, 300f); if (tempPosition.IsSafeEx()) { endPosition = tempPosition; } } } } #endregion #region Couldn't find an ally, tumble inside bush var AmInBush = NavMesh.IsWallOfGrass(ObjectManager.Player.ServerPosition, 33); var closeEnemies = TumbleVariables.EnemiesClose.ToList(); if (!AmInBush && endPosition == Vector3.Zero) { var PositionsComplete = TumbleHelper.GetCompleteRotatedQPositions(); foreach (var position in PositionsComplete) { if (NavMesh.IsWallOfGrass(position, 33) && closeEnemies.All( m => m.LSDistance(position) > 340f && !NavMesh.IsWallOfGrass(m.ServerPosition, 40)) && !WardTrackerVariables.detectedWards.Any( m => NavMesh.IsWallOfGrass(m.Position, 33) && m.Position.LSDistance(position) < m.WardTypeW.WardVisionRange && !(m.WardTypeW.WardType == WardType.ShacoBox || m.WardTypeW.WardType == WardType.TeemoShroom))) { if (position.IsSafe()) { endPosition = position; break; } } } } #endregion #region Couldn't even tumble to ally, just go to mouse if (endPosition == Vector3.Zero) { var mousePosition = ObjectManager.Player.ServerPosition.LSExtend(Game.CursorPos, 300f); if (mousePosition.IsSafe()) { endPosition = mousePosition; } } #endregion if (ObjectManager.Player.HealthPercent < 10 && ObjectManager.Player.CountEnemiesInRange(1500) > 1) { var position = ObjectManager.Player.ServerPosition.LSExtend(Game.CursorPos, 300f); return(position.IsSafeEx() ? position : endPosition); } return(endPosition); }
void Move() { if (!moveTarget) { CreateMoveTarget(); } else if (moveTarget.gameObject.activeInHierarchy == false) { moveTarget.gameObject.SetActive(true); } if (movementType == MovementTypes.Ground) { if (!m_navAgent) { m_navAgent = gameObject.AddComponent <NavMeshAgent>(); m_navAgent.speed = moveSpeed; m_navAgent.angularSpeed = turnSpeed; } else if (!m_navAgent.isActiveAndEnabled) { m_navAgent.enabled = true; if (m_navAgent.speed != moveSpeed) { m_navAgent.speed = moveSpeed; } if (m_navAgent.angularSpeed != turnSpeed) { m_navAgent.angularSpeed = turnSpeed; } } else if (m_navAgent && moveTarget) { if (m_navAgent.speed != moveSpeed) { m_navAgent.speed = moveSpeed; } if (m_navAgent.angularSpeed != turnSpeed) { m_navAgent.angularSpeed = turnSpeed; } Debug.DrawLine(transform.position, moveTarget.position, Color.red); if (m_navAgent.isOnNavMesh) { m_navAgent.stoppingDistance = 0; m_navAgent.SetDestination(moveTarget.position); } else { NavMeshHit hit; if (NavMesh.SamplePosition(transform.position, out hit, 1000f, m_navAgent.areaMask)) { m_navAgent.enabled = false; transform.position = hit.position; Invoke("NavOn", 0.1f); } else { if (rankState != RankState.IsGeneral && myGeneral) { m_navAgent.enabled = false; transform.position = moveTarget.position; Invoke("NavOn", 0.1f); } } } if (Vector3.Distance(new Vector3(moveTarget.position.x, transform.position.y, moveTarget.position.z), transform.position) > moveSpeed * Time.deltaTime) { moving = true; } else { moving = false; } } LookAtMoveTarget(); } if (movementType == MovementTypes.Air) { if (m_navAgent) { m_navAgent.enabled = false; } if (moveTarget) { LookAtMoveTarget(); } if (ClearLineOfSight()) { if (attackType == AttackType.AUTO) { MoveTowardsMoveTarget(); } else { if (Vector3.Distance(moveTarget.position, transform.position) > guns[0].attackRangeMin) { MoveTowardsMoveTarget(); } } } else { Evade(); } } if (moving) { OnMove.Invoke(); } }
internal static void Flee() { if (!ES.CatForm() && ES.Spells["Aspect"].IsReady() && ES.SpellTimer["Pounce"].IsReady()) { ES.Spells["Aspect"].Cast(); } var wallCheck = ES.GetFirstWallPoint(ES.Player.Position, Game.CursorPos); if (wallCheck != null) { wallCheck = ES.GetFirstWallPoint((Vector3)wallCheck, Game.CursorPos, 5); } var movePosition = wallCheck != null ? (Vector3)wallCheck : Game.CursorPos; var tempGrid = NavMesh.WorldToGrid(movePosition.X, movePosition.Y); var fleeTargetPosition = NavMesh.GridToWorld((short)tempGrid.X, (short)tempGrid.Y); Obj_AI_Base target = null; var wallJumpPossible = false; if (ES.CatForm() && ES.SpellTimer["Pounce"].IsReady() && wallCheck != null) { var wallPosition = movePosition; var direction = (Game.CursorPos.To2D() - wallPosition.To2D()).Normalized(); float maxAngle = 80f; float step = maxAngle / 20; float currentAngle = 0; float currentStep = 0; bool jumpTriggered = false; while (true) { if (currentStep > maxAngle && currentAngle < 0) { break; } if ((currentAngle == 0 || currentAngle < 0) && currentStep != 0) { currentAngle = (currentStep) * (float)Math.PI / 180; currentStep += step; } else if (currentAngle > 0) { currentAngle = -currentAngle; } Vector3 checkPoint; if (currentStep == 0) { currentStep = step; checkPoint = wallPosition + ES.Spells["Pounce"].Range * direction.To3D(); } else { checkPoint = wallPosition + ES.Spells["Pounce"].Range * direction.Rotated(currentAngle).To3D(); } if (checkPoint.IsWall()) { continue; } wallCheck = ES.GetFirstWallPoint(checkPoint, wallPosition); if (wallCheck == null) { continue; } var wallPositionOpposite = (Vector3)ES.GetFirstWallPoint((Vector3)wallCheck, wallPosition, 5); if (ES.Player.GetPath(wallPositionOpposite).ToList().To2D().PathLength() - ES.Player.Distance(wallPositionOpposite) > 200) { if (ES.Player.Distance(wallPositionOpposite) < ES.Spells["Pounce"].Range - ES.Player.BoundingRadius / 2) { ES.Spells["Pounce"].Cast(wallPositionOpposite); jumpTriggered = true; break; } else { wallJumpPossible = true; } } else { Render.Circle.DrawCircle(Game.CursorPos, 35, Color.Red, 2); } } if (!jumpTriggered) { Orbwalking.Orbwalk(target, Game.CursorPos, 90f, 0f, false, false); } } else { Orbwalking.Orbwalk(target, Game.CursorPos, 90f, 0f, false, false); if (ES.CatForm() && ES.SpellTimer["Pounce"].IsReady()) { ES.Spells["Pounce"].Cast(Game.CursorPos); } } }
bool CheckReachablePoint(Vector3 destination) { return(NavMesh.CalculatePath(transform.position, destination, NavMesh.AllAreas, new NavMeshPath())); }
/// <summary> /// Start method. /// </summary> void Start() { ResetStopIndex(); navAgent.speed = profile.speed; navAgent.radius = 0.75f + Random.Range(-0.25f, 0.25f); //Randomize "personal space" if (routing != null) { if (routing.itinerary != null) { stations = routing.itinerary.WayPoints; } } // Calculate the road mask (used if car awareness is active) roadMask = 1 << NavMesh.GetAreaFromName("vehicle road") | 1 << NavMesh.GetAreaFromName("residential") | 1 << NavMesh.GetAreaFromName("service") | 1 << NavMesh.GetAreaFromName("crosswalk"); UpdateInfoBalloon(); currentWeather = FlashPedestriansGlobalParameters.WeatherConditions.DefaultWeather; }
// Update is called once per frame void Update() { if (attack) { //if enemy reach it's destination set walking aniamtions off and rotate the enemy to face the player if (Vector3.Distance(transform.position, AI.destination) <= 1.25f) { anim.SetBool("Walk", false); float angle = Mathf.Atan2(transform.position.z - Player.transform.position.z, transform.position.x - Player.transform.position.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0, -angle - 77.5f, 0); //if player choose not to take cover, if (!hide) { //we shoot a linecast from the enemy to the player to check if there is a direct line of sights, if not we reposition the enemy if (Physics.Linecast(Point.transform.position, Player.transform.position, LM) && nttm <= Time.time) { //this block of code does a continues loop until they find a position on the navmesh that has a direct line of sights to the player Vector3 finalPosition = transform.position; var t = 0; while (true) { t++; float ran = Random.Range(5f, 50f); Vector3 randomDirection = Random.insideUnitSphere * ran; randomDirection += this.transform.position; NavMeshHit hit; NavMesh.SamplePosition(randomDirection, out hit, ran, NavMesh.AllAreas); finalPosition = hit.position; if (!Physics.Linecast(finalPosition, Player.transform.position) || t >= 666) { break; } } nttm = Time.time + 10f; AI.SetDestination(finalPosition); //aet the next time to reposition to take cover hide = true; } else { //if there is a direct line of sight, shoot player if (ntts <= Time.time && !Physics.Linecast(Point.transform.position + new Vector3(0, 1, 0), Player.transform.position, LM)) { StartCoroutine(shoot()); } } } else { if (nttm <= Time.time) { //if player choose to take cover, we shoot a linecast from the enemy to the player to check if there is a direct line of sights, if so we reposition the enemy if (!Physics.Linecast(Point.transform.position, Player.transform.position, LM)) { //this block of code does a continues loop until they find a position on the navmesh that has no direct line of sights to the player Vector3 finalPosition = transform.position; var t = 0; while (true) { t++; float ran = Random.Range(5f, 50f); Vector3 randomDirection = Random.insideUnitSphere * ran; randomDirection += this.transform.position; NavMeshHit hit; NavMesh.SamplePosition(randomDirection, out hit, ran, NavMesh.AllAreas); finalPosition = hit.position; if (Physics.Linecast(finalPosition, Player.transform.position) || t >= 666) { break; } } nttm = Time.time + 10f; AI.SetDestination(finalPosition); hide = false; } } else { ///else shoot if (ntts <= Time.time && !Physics.Linecast(Point.transform.position + new Vector3(0, 1, 0), Player.transform.position, LM)) { StartCoroutine(shoot()); } } } } else { //if enemy have not reach their destination, play walking aniamtions anim.SetBool("Walk", true); } } //we health is less then 1, they DIE!!!!!!!!!! if (Health <= 0) { Died(); } //if enemy is hurt spawn a blood decal on the floor if (Health < MaxHealth) { attack = true; MaxHealth = Health; RaycastHit hit; if (Physics.Raycast(Point.transform.position, Vector3.down, out hit, 2.5f, LM)) { Instantiate(BloodDecal, hit.point, Quaternion.LookRotation(hit.normal)); } } }
public static Vector3 GetClosestNavMeshPoint(Vector3 naivePoint) { if (NavMesh.SamplePosition(naivePoint, out NavMeshHit navHit, 25f, NavMesh.AllAreas)) { return(navHit.position); }
void Awake() { this.BorderVectors = FindNavMeshBorders(NavMesh.CalculateTriangulation()); }
private int showDrop(Vector3 dropPos, int wrongcount, int idx, DropItemdta item, bool isfake = false) { if (lDropOffset.Count <= idx) { idx = 0; } Vector3 vec = dropPos + lDropOffset[idx]; // GameObject go = GameObject.Find("coin"); Vector3 begin = vec; begin.y = -99; NavMeshHit hit; //if (NavMesh.Raycast(begin, vec, out hit, NavMesh.GetNavMeshLayerFromName("Default"))) NavMesh.SamplePosition(vec, out hit, 100f, NavmeshUtils.allARE); Vector3 pos = hit.position; if (pos.x == vec.x && pos.z == vec.z) { vec.y = pos.y; DropItem itm = getDropItem(vec, Vector3.zero, item, isfake); DropItemUIMgr.getInstance().show(itm, itm.itemdta.getDropItemName()); if (!isfake) { dDropItem[item.dpid] = itm; if (item.ownerId == PlayerModel.getInstance().cid || item.ownerId == 0 || (TeamProxy.getInstance().MyTeamData != null && item.ownerId == TeamProxy.getInstance().MyTeamData.teamId)) { dDropItem_own[item.dpid] = itm; } } else { item.dpid = fakeItemIdx; dDropFakeItem[item.dpid] = itm; fakeItemIdx++; } return(idx + 1); } else if (wrongcount >= 3) { debug.Log(":" + item.dpid); DropItem itm = getDropItem(pos, Vector3.zero, item); DropItemUIMgr.getInstance().show(itm, itm.itemdta.getDropItemName()); if (!isfake) { dDropItem[item.dpid] = itm; //if (item.ownerId == PlayerModel.getInstance().cid) //{ //dDropItem_own[item.dpid] = itm; if (item.ownerId == PlayerModel.getInstance().cid || item.ownerId == 0 || (TeamProxy.getInstance().MyTeamData != null && item.ownerId == TeamProxy.getInstance().MyTeamData.teamId)) { dDropItem_own[item.dpid] = itm; } //} } else { item.dpid = fakeItemIdx; dDropFakeItem[item.dpid] = itm; fakeItemIdx++; } return(idx + 1); } wrongcount++; return(showDrop(dropPos, wrongcount, idx + 1, item, isfake)); }
public override void OnInspectorGUI() { if (s_Styles == null) { s_Styles = new Styles(); } serializedObject.Update(); var bs = NavMesh.GetSettingsByID(m_AgentTypeID.intValue); if (bs.agentTypeID != -1) { // Draw image const float diagramHeight = 80.0f; Rect agentDiagramRect = EditorGUILayout.GetControlRect(false, diagramHeight); NavMeshEditorHelpers.DrawAgentDiagram(agentDiagramRect, bs.agentRadius, bs.agentHeight, bs.agentClimb, bs.agentSlope); } NavMeshComponentsGUIUtility.AgentTypePopup("Agent Type", m_AgentTypeID); EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_CollectObjects); if ((CollectObjects)m_CollectObjects.enumValueIndex == CollectObjects.Volume) { EditorGUI.indentLevel++; InspectorEditButtonGUI(); EditorGUILayout.PropertyField(m_Size); EditorGUILayout.PropertyField(m_Center); } else { if (editingCollider) { EditMode.QuitEditMode(); } } EditorGUILayout.PropertyField(m_LayerMask, s_Styles.m_LayerMask); EditorGUILayout.PropertyField(m_UseGeometry); EditorGUILayout.Space(); EditorGUILayout.Space(); m_OverrideVoxelSize.isExpanded = EditorGUILayout.Foldout(m_OverrideVoxelSize.isExpanded, "Advanced"); if (m_OverrideVoxelSize.isExpanded) { EditorGUI.indentLevel++; NavMeshComponentsGUIUtility.AreaPopup("Default Area", m_DefaultArea); // Override voxel size. EditorGUILayout.PropertyField(m_OverrideVoxelSize); using (new EditorGUI.DisabledScope(!m_OverrideVoxelSize.boolValue || m_OverrideVoxelSize.hasMultipleDifferentValues)) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_VoxelSize); if (!m_OverrideVoxelSize.hasMultipleDifferentValues) { if (!m_AgentTypeID.hasMultipleDifferentValues) { float voxelsPerRadius = m_VoxelSize.floatValue > 0.0f ? (bs.agentRadius / m_VoxelSize.floatValue) : 0.0f; EditorGUILayout.LabelField(" ", voxelsPerRadius.ToString("0.00") + " voxels per agent radius", EditorStyles.miniLabel); } if (m_OverrideVoxelSize.boolValue) { EditorGUILayout.HelpBox("Voxel size controls how accurately the navigation mesh is generated from the level geometry. A good voxel size is 2-4 voxels per agent radius. Making voxel size smaller will increase build time.", MessageType.None); } } EditorGUI.indentLevel--; } // Override tile size EditorGUILayout.PropertyField(m_OverrideTileSize); using (new EditorGUI.DisabledScope(!m_OverrideTileSize.boolValue || m_OverrideTileSize.hasMultipleDifferentValues)) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_TileSize); if (!m_TileSize.hasMultipleDifferentValues && !m_VoxelSize.hasMultipleDifferentValues) { float tileWorldSize = m_TileSize.intValue * m_VoxelSize.floatValue; EditorGUILayout.LabelField(" ", tileWorldSize.ToString("0.00") + " world units", EditorStyles.miniLabel); } if (!m_OverrideTileSize.hasMultipleDifferentValues) { if (m_OverrideTileSize.boolValue) { EditorGUILayout.HelpBox("Tile size controls the how local the changes to the world are (rebuild or carve). Small tile size allows more local changes, while potentially generating more data in overal.", MessageType.None); } } EditorGUI.indentLevel--; } // Height mesh using (new EditorGUI.DisabledScope(true)) { EditorGUILayout.PropertyField(m_BuildHeightMesh); } EditorGUILayout.Space(); EditorGUI.indentLevel--; } EditorGUILayout.Space(); serializedObject.ApplyModifiedProperties(); var hadError = false; var multipleTargets = targets.Length > 1; foreach (NavMeshSurface navSurface in targets) { var settings = navSurface.GetBuildSettings(); // Calculating bounds is potentially expensive when unbounded - so here we just use the center/size. // It means the validation is not checking vertical voxel limit correctly when the surface is set to something else than "in volume". var bounds = new Bounds(Vector3.zero, Vector3.zero); if (navSurface.collectObjects == CollectObjects.Volume) { bounds = new Bounds(navSurface.center, navSurface.size); } var errors = settings.ValidationReport(bounds); if (errors.Length > 0) { if (multipleTargets) { EditorGUILayout.LabelField(navSurface.name); } foreach (var err in errors) { EditorGUILayout.HelpBox(err, MessageType.Warning); } GUILayout.BeginHorizontal(); GUILayout.Space(EditorGUIUtility.labelWidth); if (GUILayout.Button("Open Agent Settings...", EditorStyles.miniButton)) { NavMeshEditorHelpers.OpenAgentSettings(navSurface.agentTypeID); } GUILayout.EndHorizontal(); hadError = true; } } if (hadError) { EditorGUILayout.Space(); } using (new EditorGUI.DisabledScope(Application.isPlaying || m_AgentTypeID.intValue == -1)) { GUILayout.BeginHorizontal(); GUILayout.Space(EditorGUIUtility.labelWidth); if (GUILayout.Button("Clear")) { foreach (NavMeshSurface s in targets) { ClearSurface(s); } SceneView.RepaintAll(); } if (GUILayout.Button("Bake")) { // Remove first to avoid double registration of the callback EditorApplication.update -= UpdateAsyncBuildOperations; EditorApplication.update += UpdateAsyncBuildOperations; foreach (NavMeshSurface surf in targets) { var oper = new AsyncBakeOperation(); oper.bakeData = InitializeBakeData(surf); oper.bakeOperation = surf.UpdateNavMesh(oper.bakeData); oper.surface = surf; s_BakeOperations.Add(oper); } } GUILayout.EndHorizontal(); } // Show progress for the selected targets for (int i = s_BakeOperations.Count - 1; i >= 0; --i) { if (!targets.Contains(s_BakeOperations[i].surface)) { continue; } var oper = s_BakeOperations[i].bakeOperation; if (oper == null) { continue; } var p = oper.progress; if (oper.isDone) { SceneView.RepaintAll(); continue; } GUILayout.BeginHorizontal(); if (GUILayout.Button("Cancel", EditorStyles.miniButton)) { var bakeData = s_BakeOperations[i].bakeData; UnityEngine.AI.NavMeshBuilder.Cancel(bakeData); s_BakeOperations.RemoveAt(i); } EditorGUI.ProgressBar(EditorGUILayout.GetControlRect(), p, "Baking: " + (int)(100 * p) + "%"); if (p <= 1) { Repaint(); } GUILayout.EndHorizontal(); } }
public static bool IsMoveable(Vector3 position) { NavMeshHit hit; bool isa = NavMesh.SamplePosition(position, out hit, 1f, -1); log.Debug("____________________________________" + hit.hit + "_________" + isa + "__" + position.ToString() + "___" + NavMesh.GetNavMeshLayerFromName("Default")); return(hit.hit); }
/// <inheritdoc /> public override void Enter(QuestNpcParams p) { p.NavAgent.isStopped = false; if (p.MovementType == MovementType.Wander || p.MovementType == MovementType.NoLimitsWander) { Vector3 randomOffset = Random.insideUnitSphere * p.WanderDistance; Vector3 randomWanderPosistion = randomOffset += p.NpcTransform.position; NavMeshHit hit; while (NavMesh.SamplePosition(randomWanderPosistion, out hit, 1, NavMesh.AllAreas) == false && Vector3.Distance(randomWanderPosistion, p.OriginPosistion) > p.WanderDistance || NavMesh.SamplePosition(randomWanderPosistion, out hit, 1, NavMesh.AllAreas) == false) { randomOffset = Random.insideUnitSphere * p.WanderDistance; randomWanderPosistion = randomOffset += p.NpcTransform.position; } if (p.NavAgent.SetDestination(randomWanderPosistion)) { Parent.SetState(typeof(Idle), p); } else { Debug.LogError("Error occured when setting destination of navmesh agent."); } } else if (p.MovementType == MovementType.Patrol) { p.CurrentPatrolPoint++; if (p.CurrentPatrolPoint > p.PatrolPoints.Count - 1) { p.CurrentPatrolPoint = 0; } NavMeshHit hit; if (NavMesh.SamplePosition(p.PatrolPoints[p.CurrentPatrolPoint], out hit, p.WanderDistance, NavMesh.AllAreas)) { if (p.NavAgent.SetDestination(p.PatrolPoints[p.CurrentPatrolPoint])) { Parent.SetState(typeof(Idle), p); } else { Debug.LogError("Error occured when setting destination of navmesh agent."); } } else { Debug.LogError("Error occured when sampling posistion to get nearest navmesh point."); } } }
public void UpdatePath(bool keepOldIfNotFound) { if (m_IsInitialized) { NavMeshPath path = new NavMeshPath(); Vector3 startPosition = ARSpaceToUnity(m_ARSpace.transform, m_ARSpace.initialOffset, m_CameraTransform.position); Vector3 targetPosition = ARSpaceToUnity(m_ARSpace.transform, m_ARSpace.initialOffset, m_TargetTransform.position); Vector3 currentPositionInUnitySpace = ARSpaceToUnity(m_ARSpace.transform, m_ARSpace.initialOffset, m_CameraTransform.position); Vector3 delta = targetPosition - currentPositionInUnitySpace; float distanceToTarget = new Vector3(delta.x, 0f, delta.z).magnitude; if (!m_NavigationArrived && distanceToTarget < navigationManager.arrivedDistanceThreshold) { m_NavigationArrived = true; navigationManager.DisplayArrivedNotification(); return; } if (NavMesh.CalculatePath(startPosition, targetPosition, NavMesh.AllAreas, path)) { if (!m_NavigationStarted) { navigationManager.DisplayNavigation(); m_NavigationStarted = true; m_NavigationArrived = false; } m_IsNavigating = true; List <Vector3> corners = new List <Vector3>(path.corners); List <Vector3> collapsedCorners = new List <Vector3>(); for (int i = 0; i < corners.Count; i++) { corners[i] = corners[i] + new Vector3(0f, m_yOffset, 0f); corners[i] = UnityToARSpace(m_ARSpace.transform, m_ARSpace.initialOffset, corners[i]); } for (int i = 0; i < corners.Count - 1; i++) { Vector3 cp = corners[i]; Vector3 np = corners[i + 1]; float threshold = 0.75f; if (Vector3.Distance(cp, np) > threshold) { collapsedCorners.Add(cp); //Debug.DrawLine(cp, cp + Vector3.up, Color.red); } } collapsedCorners.Add(corners[corners.Count - 1]); m_PathMeshGenerator.GeneratePath(collapsedCorners, m_ARSpace.transform.up); // update compass m_Arrow direction if (m_Arrow != null && !m_Arrow.activeInHierarchy) { m_Arrow.SetActive(true); } if (corners.Count > 1 && m_ArrowDirection != null) { Vector3 nextPoint = new Vector3(corners[1].x, Camera.main.transform.position.y, corners[1].z); m_ArrowDirection.LookAt(nextPoint, Vector3.up); } } else { if (!keepOldIfNotFound) { navigationManager.DisplayPathNotFoundNotification(); } } } }
public void ClearNav() { NavMesh.RemoveAllNavMeshData(); }
// -------------------------------------------------------------------------------- // Name : OnSceneGUI // Desc : Implementing this functions means the Unity Editor will call it when // the Scene View is being repainted. This gives us a hook to do our // own rendering to the scene view. // -------------------------------------------------------------------------------- void OnSceneGUI() { // Get a reference to the component being rendered AIWaypointNetwork network = (AIWaypointNetwork)target; // Fetch all waypoints from the network and render a label for each one for (int i = 0; i < network.Waypoints.Count; i++) { if (network.Waypoints[i] != null) { Handles.Label(network.Waypoints[i].position, "Waypoint " + i.ToString()); } } // If we are in connections mode then we will to draw lines // connecting all waypoints if (network.DisplayMode == PathDisplayMode.Connections) { // Allocate array of vector to store the polyline positions Vector3 [] linePoints = new Vector3[network.Waypoints.Count + 1]; // Loop through each waypoint + one additional interation for (int i = 0; i <= network.Waypoints.Count; i++) { // Calculate the waypoint index with wrap-around in the // last loop iteration int index = i != network.Waypoints.Count ? i : 0; // Fetch the position of the waypoint for this iteration and // copy into our vector array. if (network.Waypoints[index] != null) { linePoints[i] = network.Waypoints[index].position; } else { linePoints[i] = new Vector3(Mathf.Infinity, Mathf.Infinity, Mathf.Infinity); } } // Set the Handle color to Cyan Handles.color = Color.cyan; // Render the polyline in the scene view by passing in our list of waypoint positions Handles.DrawPolyLine(linePoints); } else // We are in paths mode so to proper navmesh path search and render result if (network.DisplayMode == PathDisplayMode.Paths) { // Allocate a new NavMeshPath NavMeshPath path = new NavMeshPath(); // Assuming both the start and end waypoint indices selected are ligit if (network.Waypoints[network.UIStart] != null && network.Waypoints[network.UIEnd] != null) { // Fetch their positions from the waypoint network Vector3 from = network.Waypoints[network.UIStart].position; Vector3 to = network.Waypoints[network.UIEnd].position; // Request a path search on the nav mesh. This will return the path between // from and to vectors NavMesh.CalculatePath(from, to, NavMesh.AllAreas, path); // Set Handles color to Yellow Handles.color = Color.yellow; // Draw a polyline passing int he path's corner points Handles.DrawPolyLine(path.corners); } } }
void Start() { triangulation = NavMesh.CalculateTriangulation(); }
private static void CreateList( AgentActor agent, List <ActionPoint> source, List <ActionPoint> destination, EventType eventType, bool isFollow, bool isRain) { int chunkId = agent.ChunkID; Dictionary <int, bool> toRelease = DictionaryPool <int, bool> .Get(); int searchCount = Singleton <Manager.Map> .Instance.EnvironmentProfile.SearchCount; float meshSampleDistance = Singleton <Resources> .Instance.LocomotionProfile.ActionPointNavMeshSampleDistance; foreach (ActionPoint actionPoint1 in source) { if (!Object.op_Equality((Object)actionPoint1, (Object)null) && !Object.op_Equality((Object)actionPoint1.OwnerArea, (Object)null) && (actionPoint1.IsNeutralCommand && !actionPoint1.IsReserved(agent))) { List <ActionPoint> connectedActionPoints = actionPoint1.ConnectedActionPoints; if (!connectedActionPoints.IsNullOrEmpty <ActionPoint>()) { bool flag = false; foreach (ActionPoint actionPoint2 in connectedActionPoints) { if (!Object.op_Equality((Object)actionPoint2, (Object)null) && (!actionPoint2.IsNeutralCommand || actionPoint2.IsReserved(agent))) { flag = true; break; } } if (flag) { continue; } } if (!isRain || actionPoint1.AreaType == MapArea.AreaType.Indoor) { MapArea ownerArea = actionPoint1.OwnerArea; bool flag1; if (!toRelease.TryGetValue(ownerArea.AreaID, out flag1)) { toRelease[ownerArea.AreaID] = flag1 = Singleton <Manager.Map> .Instance.CheckAvailableMapArea(ownerArea.AreaID); } if (flag1 && (!isFollow ? actionPoint1.AgentEventType : actionPoint1.AgentDateEventType).Contains(eventType)) { switch (eventType) { case EventType.Eat: StuffItem carryingItem = agent.AgentData.CarryingItem; AgentProfile agentProfile = Singleton <Resources> .Instance.AgentProfile; ItemIDKeyPair[] canStandEatItems = Singleton <Resources> .Instance.AgentProfile.CanStandEatItems; bool flag2 = false; foreach (ItemIDKeyPair itemIdKeyPair in canStandEatItems) { if (carryingItem.CategoryID == itemIdKeyPair.categoryID && carryingItem.ID == itemIdKeyPair.itemID) { flag2 = true; break; } } ActionPointInfo outInfo; if (flag2) { PoseKeyPair eatDeskId1 = agentProfile.PoseIDTable.EatDeskID; PoseKeyPair eatDeskId2 = agentProfile.PoseIDTable.EatDeskID; if (actionPoint1.FindAgentActionPointInfo(EventType.Eat, eatDeskId1.poseID, out outInfo) || actionPoint1.FindAgentActionPointInfo(EventType.Eat, eatDeskId2.poseID, out outInfo)) { break; } continue; } PoseKeyPair eatDishId = agentProfile.PoseIDTable.EatDishID; if (actionPoint1.FindAgentActionPointInfo(EventType.Eat, eatDishId.poseID, out outInfo)) { break; } continue; case EventType.Search: SearchActionPoint searchActionPoint = actionPoint1 as SearchActionPoint; if (Object.op_Inequality((Object)searchActionPoint, (Object)null)) { int registerId = searchActionPoint.RegisterID; Dictionary <int, AIProject.SaveData.Environment.SearchActionInfo> searchActionLockTable = agent.AgentData.SearchActionLockTable; AIProject.SaveData.Environment.SearchActionInfo searchActionInfo1; if (!searchActionLockTable.TryGetValue(registerId, out searchActionInfo1)) { AIProject.SaveData.Environment.SearchActionInfo searchActionInfo2 = new AIProject.SaveData.Environment.SearchActionInfo(); searchActionLockTable[registerId] = searchActionInfo2; searchActionInfo1 = searchActionInfo2; } if (searchActionInfo1.Count < searchCount) { int tableId = searchActionPoint.TableID; StuffItem itemInfo = agent.AgentData.EquipedSearchItem(tableId); if (agent.SearchAreaID == 0) { if (tableId != 0 && tableId != 1 && tableId != 2 || !searchActionPoint.CanSearch(EventType.Search, itemInfo)) { continue; } break; } if (agent.SearchAreaID != searchActionPoint.TableID || !searchActionPoint.CanSearch(EventType.Search, itemInfo)) { continue; } break; } continue; } break; case EventType.Warp: WarpPoint warpPoint = actionPoint1 as WarpPoint; Dictionary <int, List <WarpPoint> > dictionary; List <WarpPoint> warpPointList; if (!Object.op_Inequality((Object)warpPoint, (Object)null) || !Singleton <Manager.Map> .Instance.WarpPointDic.TryGetValue(ownerArea.ChunkID, out dictionary) || (!dictionary.TryGetValue(warpPoint.TableID, out warpPointList) || warpPointList.Count < 2)) { continue; } break; } if (SetDesiredRandomAction._navMeshPath == null) { SetDesiredRandomAction._navMeshPath = new NavMeshPath(); } NavMeshHit navMeshHit; if (agent.NavMeshAgent.CalculatePath(actionPoint1.LocatedPosition, SetDesiredRandomAction._navMeshPath) && SetDesiredRandomAction._navMeshPath.get_status() == null && NavMesh.SamplePosition(actionPoint1.LocatedPosition, ref navMeshHit, meshSampleDistance, agent.NavMeshAgent.get_areaMask())) { destination.Add(actionPoint1); } } } } } DictionaryPool <int, bool> .Release(toRelease); }
public Pather(string continent) { Continent = continent; DetourMesh = new NavMesh(); DetourMesh.Init(Origin, TileSize, TileSize, 2048, 16384, 4194304); Filter = QueryFilter.Default; }