public override void Sink() { if (!(_state is SinkingState)) { _state = new SinkingState(this); } }
protected void SpawnShip(string msnShip, Vector3?spawnpos, Quaternion?spawnorient, string objList, MissionScript script, MissionRuntime runtime) { var ship = script.Ships[msnShip]; var npcDef = script.NPCs[ship.NPC]; script.NpcShips.TryGetValue(npcDef.NpcShipArch, out var shipArch); if (shipArch == null) { shipArch = runtime.Player.Game.GameData.Ini.NPCShips.ShipArches.First(x => x.Nickname.Equals(npcDef.NpcShipArch, StringComparison.OrdinalIgnoreCase)); } var pos = spawnpos ?? ship.Position; var orient = spawnorient ?? ship.Orientation; AiState state = null; if (!string.IsNullOrEmpty(objList)) { state = script.ObjLists[objList].Construct(); } runtime.Player.WorldAction(() => { runtime.Player.World.Server.GameData.TryGetLoadout(shipArch.Loadout, out var ld); var pilot = runtime.Player.World.Server.GameData.GetPilot(shipArch.Pilot); var obj = runtime.Player.World.NPCs.DoSpawn(ship.Nickname, ld, pilot, pos, orient); obj.GetComponent <SNPCComponent>().SetState(state); }); }
void Update() { // Update state AiState nextState = _state.Update(); // Turn towards the desired heading float targetTurningSpeed; float distanceToTargetHeading = Util.AngleDist(_helper.Heading, _state.DesiredHeading); if (distanceToTargetHeading > _AiSettings.SlowRadius) { targetTurningSpeed = _AiSettings.MaxRotationSpeed; } else { targetTurningSpeed = _AiSettings.MaxRotationSpeed * distanceToTargetHeading / _AiSettings.SlowRadius * 0.8f; } targetTurningSpeed *= Util.GetTurnDirection(_helper.Heading, _state.DesiredHeading); RequestedTurningSpeed = targetTurningSpeed; // Update speed to desired amount RequestedSpeed = _state.DesiredSpeed; // Change state to next _state = nextState; // Animate model _Caravel.TargetRudderTilt = 0; _Caravel.TargetAimPos = _helper.TargetPos; _Caravel.CannonballSpeed = _AiSettings.CannonballSpeed; _Caravel.CannonballGravity = _AiSettings.CannonballGravity; _Caravel.CannonMaxFiringAngle = _AiSettings.MaxFiringAngle; }
void Start() { _helper = new AiHelper(this.gameObject, _Player, _AiSettings); _state = new PursueState(this, _helper); _lastFireTime = float.MinValue; }
public void StressTest() { AiBrain[] b = new AiBrain[StressTestSize]; AiState[] s = new AiState[StressTestSize]; DummyInterface dummy = new DummyInterface(); AiCore.InitCore(); Thread thread = new Thread(AiCore.Run); thread.Start(); for (int i = 0; i < StressTestSize; i++) { s[i] = new AiState(template, "0"); b[i] = new AiBrain(dummy, s[i]); AiCore.AddBrain(b[i]); } Thread.Sleep(1000); AiCore.Shutdown(); for (int i = 0; i < StressTestSize; i++) { Assert.AreEqual(10, ((Accumulator)s[i].nodes["0"]).val); } thread.Join(); }
void TakeDamage(Hit hit) { Debug.Log("Took " + hit.Damage + " damage."); if (hit.Initiator == gameObject) { // self damage Health -= (int)(hit.Damage * .33f); } else { Health -= (int)hit.Damage; } if (Health <= 0) { Debug.Log("Dead"); Destroy(gameObject); } // if not in combat, do combat search in direction of the attacker if (state != AiState.Combat) { state = AiState.CombatSearching; // look in direction of shot faceDirection = player.transform.position - transform.position; // lastKnownPlayerPosition = faceDirection.normalized * Helper.RandomInt(10, 50); } }
void Hunting() { seeHearRange = seeHearRangeBackup; if (Vector3.Distance(transform.position, playersTransform.position) < closeEnoughRange) { inRange = true; } else { inRange = false; } if (inRange) { meshAgent.destination = transform.position; } else { meshAgent.destination = lastKnownPlayerLocation; if (meshAgent.remainingDistance < .5f) { aiState = AiState.idle; } } TakeAShot(); lastAiState = AiState.hunting; }
// Use this for initialization void Start() { agent = GetComponent <NavMeshAgent>(); gc = GameObject.FindObjectOfType <GameController>(); ECurrentAiState = AiState.Patroling; targetTransform = SelectRandomPatrolPointTarget(); }
public void UpdateWaypoints(long Tick) { if (State == AiState.STANDING || State == AiState.MOVING) { if (Waypoints.Count == 0) { return; } //System.Diagnostics.Trace.Assert(_Owner.Name != "Heinz Lutzen"); if (CurrentWaypoint != null && IsAtWaypointEnd()) { EndWaypoint(Tick); } if (CanStartNextWaypoint(Tick)) { SetNextWaypoint(Tick); } if (State == AiState.MOVING && !_unit.MvtInterface.IsMoving) { State = AiState.STANDING; } if (State == AiState.STANDING && CurrentWaypoint != null) { StartWaypoint(Tick); } } }
public void Update() { switch (_currentState) { case AiState.Moving: Moving(); _animator.SetBool(_walkAnimation, true); _animator.SetBool(_attackAnimation, false); break; case AiState.Attacking: Attacking(); _animator.SetBool(_walkAnimation, false); _animator.SetBool(_attackAnimation, true); break; case AiState.Spawned: if (Math.Abs(Distance) > 0) { _currentState = AiState.Moving; } break; case AiState.Celebrating: _animator.SetBool(_walkAnimation, false); _animator.SetBool(_attackAnimation, false); break; default: throw new ArgumentOutOfRangeException(); } }
IEnumerator TaskRunner() { yield return(new WaitForSeconds(intervalTime * 10)); while (true) { if (state == AiState.Ready) { if (tasks.Count > 0) { state = AiState.Execut; task = tasks.Dequeue(); Implement(task); } } else { if (task.taskComplete.Invoke()) { task.taskResult.Invoke(true); } else { if (task.waitTime < intervalTime * intervalNums) { task.taskResult.Invoke(false); Stop(); } intervalNums++; } } yield return(new WaitForSeconds(intervalTime)); } }
protected AiScript() { this.Phrases = new List <string>(); _lastBeat = DateTime.MinValue; _heartbeat = IdleHeartbeat; _heartbeatTimer = new Timer(this.Heartbeat, null, -1, -1); _rnd = new Random(RandomProvider.Get().Next()); _reactions = new Dictionary <AiState, Dictionary <AiEvent, Func <IEnumerable> > >(); _reactions[AiState.Idle] = new Dictionary <AiEvent, Func <IEnumerable> >(); _reactions[AiState.Aware] = new Dictionary <AiEvent, Func <IEnumerable> >(); _reactions[AiState.Alert] = new Dictionary <AiEvent, Func <IEnumerable> >(); _reactions[AiState.Aggro] = new Dictionary <AiEvent, Func <IEnumerable> >(); _reactions[AiState.Love] = new Dictionary <AiEvent, Func <IEnumerable> >(); _state = AiState.Idle; _aggroRadius = 500; _aggroMaxRadius = 3000; _alertDelay = TimeSpan.FromMilliseconds(8000); _hateTags = new Dictionary <string, string>(); _loveTags = new Dictionary <string, string>(); _doubtTags = new Dictionary <string, string>(); _maxDistanceFromSpawn = 3000; _aggroLimit = AggroLimit.One; }
void Thinking() { //Debug.Log("Thinking"); visitorAnimation.direction = ProjectTrader.FourDirection.Up; waitTime -= Time.deltaTime; if (waitTime <= 0) { var displayedItem = targetItemNode.displayedItem; // 구매 확률 float purchasingProbability = 0.3f; var random = UnityEngine.Random.Range(0f, 1f); if (displayedItem.ItemCount > 0 && random < purchasingProbability) { WishItems.Add(new Item() { Code = displayedItem.Item.Code, Count = 1 }); state = AiState.FindCounter; } else { state = AiState.Discard; } // 아이템 점유 해제 pathNodeManager.ItemOccupancyList[targetItemNodeIndex] = null; } }
private void OnIdle() { if (CheckTarget()) { _state = AiState.Atak; } }
void ToCounter() { // 계산원 방향 바라보기 visitorAnimation.direction = Utils.VelocityToDirection(this.transform.position - pathNodeManager.counterNode.transform.position + pathNodeManager.casherDirection); // 이동 완료후 처리 StopCoroutine(findCounterCoroutine); var currentWaitNumber = pathNodeManager.WaitQueue.Count - 1; //Debug.Log($"currentWaitNumber = {currentWaitNumber}, counterWaitNumber = {counterWaitNumber}"); // 기억했던 대기번호와 현재 대기번호가 상이하면 새로운 대기 노드 검색 if (currentWaitNumber != counterWaitNumber) { Debug.Log("ToCounter 대기노드 검색"); counterWaitNumber = currentWaitNumber; if (counterWaitNumber >= 0) { SetTarget(pathNodeManager.waitNodes[counterWaitNumber]); } else { SetTarget(targetNode = pathNodeManager.counterNode); } } pathNodeManager.WaitQueue.Enqueue(this); state = AiState.CounterWait; }
// Use this for initialization // Use this for initialization void Start() { wapon1 = GetComponentInChildren <IInputClient>(); GetComponent <InputClientManager>().ResetClient(wapon1); processor = GetComponent <LEUnitProcessorBase>(); animationPro = GetComponent <LEUnitAnimatorManager>(); animationPro.SetMotionTypeImmediately(LEUnitAnimatorManager.AnimationMotionType.IWR_0); angent = GetComponent <NavMeshAgent>(); partrolState = new AiPatrolState(this); searchState = new AISearchState(this); chaseState = new AiChaseState(this); fightState = new AiFightState(this); partrolState.Init(); searchState.Init(); chaseState.Init(); fightState.Init(); currentState = partrolState; currentState.OnStateEnter(); }
public override void EndMatch(MatchResult result, Card opponentsCard) { base.EndMatch(result, opponentsCard); if (result == MatchResult.Lose) { patience--; } else { patience++; } //Updates after a loss if (patience > 0 && stars > 3) { currentStrategyState = new BalanceState(this); } else if (patience > 0 && 3 >= stars && stars > 1) { currentStrategyState = new ConservativeState(this); } else if (patience < 0 && stars > 5) { currentStrategyState = new RecklessState(this); } else if (patience < 0 && 5 >= stars) { currentStrategyState = new AggressiveState(this); } return; }
public void hit(uint damage) { if (anim.GetBool("onCombat") == false) { anim.SetBool("onCombat", true); } state = AiState.fighting; float tmpTime = deltaTime; deltaTime = Time.time; if ((deltaTime - tmpTime) > deltaTimeProtection) { gameObject.GetComponent <AudioSource>().Play(); health -= damage; gameObject.GetComponent <Rigidbody>().AddForce(-1 * transform.forward * repulsionForce); if (health <= 0) { death(); } else { anim.SetTrigger("Hit"); } } else { anim.SetTrigger("Blocking"); } }
// Use this for initialization void Start() { ai = GetComponent <CharacterScript>(); aiState = AiState.idle; turnCoolTime = Random.Range(2, 4); }
void OnTriggerStay(Collider other) { if (other.CompareTag("PlayerUnit") && gameObject.CompareTag("EnemyUnit") && (gameObject.name == "Melee Unit" || gameObject.name == "Tank Unit")) { currentTarget = other.gameObject; if (Vector3.Distance(transform.position, currentTarget.transform.position) < 1.5f) { State = AiState.Attacking; } } else if (other.CompareTag("EnemyUnit") && gameObject.CompareTag("PlayerUnit") && (gameObject.name == "Melee Unit" || gameObject.name == "Tank Unit")) { currentTarget = other.gameObject; if (Vector3.Distance(transform.position, currentTarget.transform.position) < 1.5f) { State = AiState.Attacking; } } // Merge Functions if (other.CompareTag("PlayerUnit") && !gameObject.CompareTag("EnemyUnit")) { if (gameObject.name == "Mage Unit" && other.gameObject.name == "Mage Unit") { mergeTarget = other.gameObject; if (Vector3.Distance(transform.position, other.gameObject.transform.position) < 0.5f) { MergeUnits(other.gameObject, false); } } if (gameObject.name == "Ranged Unit" && other.gameObject.name == "Ranged Unit") { mergeTarget = other.gameObject; if (Vector3.Distance(transform.position, mergeTarget.transform.position) < 0.5f) { MergeUnits(other.gameObject, false); } } } else if (other.CompareTag("EnemyUnit") && !gameObject.CompareTag("PlayerUnit")) { if (gameObject.name == "Mage Unit" && other.gameObject.name == "Mage Unit") { mergeTarget = other.gameObject; if (Vector3.Distance(transform.position, other.gameObject.transform.position) < 0.5f) { MergeUnits(other.gameObject, true); } } if (gameObject.name == "Ranged Unit" && other.gameObject.name == "Ranged Unit") { mergeTarget = other.gameObject; if (Vector3.Distance(transform.position, mergeTarget.transform.position) < 0.5f) { MergeUnits(other.gameObject, true); } } } }
public void MageAttack() { if (currentTarget != null) { GameObject temp = Instantiate(magicPrefab, transform.position + new Vector3(0, 0.4f, 0), transform.rotation, transform); // Spawn a Magic attack. if (gameObject.tag == "EnemyUnit") { temp.GetComponent <Projectiles>().shotFrom = "Enemy"; } else if (gameObject.tag == "PlayerUnit") { temp.GetComponent <Projectiles>().shotFrom = "Player"; } } else { State = AiState.Walking; } ; //if (currentTarget.name == "Tank Unit") { // currentTarget.GetComponent<AI_AutoMove>().aiHealth -= aiDamage; //} else if (currentTarget.name == "Mage Unit" || currentTarget.name == "Ranged Unit" || currentTarget.name == "Tank Unit") { // currentTarget.GetComponent<AI_AutoMove>().aiHealth -= aiDamage * 0.5f; //} else if (currentTarget != null && currentTarget.name == "Player Castle" || currentTarget.name == "Enemy Castle") { // currentTarget.GetComponent<Tower>().TakeDamage(aiDamage); //} }
/// <summary> /// Raises the state enter event. /// </summary> /// <param name="previousState">Previous state.</param> /// <param name="newState">New state.</param> public override void OnStateEnter(AiState previousState, AiState newState) { if (path == null) { // If I have no path - try to find it path = FindObjectOfType <Pathway>(); Debug.Assert(path, "Have no path"); } if (destination == null) { // Get next waypoint from my path destination = path.GetNearestWaypoint(transform.position); } // Set destination for navigation agent aiBehavior.navAgent.destination = destination.transform.position; // Start moving aiBehavior.navAgent.move = true; aiBehavior.navAgent.turn = true; // If unit has animator if (anim != null && anim.runtimeAnimatorController != null) { // Search for clip foreach (AnimationClip clip in anim.runtimeAnimatorController.animationClips) { if (clip.name == "Move") { // Play animation anim.SetTrigger("move"); break; } } } }
public void UpdateWaypoints(long Tick) { if (State == AiState.STANDING || State == AiState.MOVING) { if (Waypoints.Count == 0) { return; } if (CurrentWaypoint != null && IsAtWaypointEnd()) { EndWaypoint(Tick); } if (CanStartNextWaypoint(Tick)) { SetNextWaypoint(Tick); } if (State == AiState.MOVING && Mvt.CurrentSpeed == 0) { State = AiState.STANDING; } if (State == AiState.STANDING && CurrentWaypoint != null) { StartWaypoint(Tick); } } }
/// <summary> /// Moves around in a certain pattern if not aggro. /// </summary> protected virtual IEnumerator PatrolArea() { currentState = AiState.Patrolling; isChasing = false; isAttacking = false; isPatrolling = true; var waitForFrames = new WaitForSeconds(patrollingPlayerSearchFrequency); if (agent != null && agent.isOnNavMesh) { agent.SetPath(GeneratePatrolPath()); } else { yield break; } while (agent.isOnNavMesh && agent.remainingDistance > patrollingTargetPositionTolerance) { if (settings.isAggressive) { SearchForPlayer(); } yield return(waitForFrames); } currentState = AiState.Idle; isPatrolling = false; if (!settings.isAggressive) { Invoke(nameof(SearchForPlayer), targetPositionUpdateInterval); } }
void Finded() { //Debug.Log("Finded"); waitTime = UnityEngine.Random.Range(0f, 1f); state = AiState.Thinking; }
/// <summary> /// Start this instance. /// </summary> void Start() { // Get all AI states from this gameobject AiState[] states = GetComponents <AiState>(); if (states.Length > 0) { foreach (AiState state in states) { // Add state to list aiStates.Add(state); } if (defaultState != null) { // Set active and previous states as default state previousState = currentState = defaultState; if (currentState != null) { // Go to active state ChangeState(currentState); } else { Debug.LogError("Incorrect default AI state " + defaultState); } } else { Debug.LogError("AI have no default state"); } } else { Debug.LogError("No AI states found"); } }
void Finding() { findingCount++; //Debug.Log("Finding"); // 랜덤 아이템 선택 targetItemNodeIndex = UnityEngine.Random.Range(0, pathNodeManager.itemNodes.Count); // TODO:해당 위치에 캐릭터가 존재하면 다시 선택하도록 수정 if (pathNodeManager.ItemOccupancyList[targetItemNodeIndex] != null) { //if (refindingCount > 100) //{ // SetTarget(pathNodeManager.exitNode); // state = AiState.Exit; //} //else state = AiState.Discard; return; } SetTarget(pathNodeManager.itemNodes[targetItemNodeIndex]); targetItemNode = targetNode as ItemNode; // 아이템 점유 pathNodeManager.ItemOccupancyList[targetItemNodeIndex] = this; state = AiState.Finded; }
void Exit() { //Debug.Log("Exit"); // 파괴절차 //Destroy(this.gameObject, 1); SpriteRenderer spriteRenderer = GetComponentInChildren <SpriteRenderer>(); StartCoroutine(Disappear()); state = AiState.None; IEnumerator Disappear() { while (true) { var color = spriteRenderer.color; color.a -= 1 / 0.2f * Time.deltaTime; if (color.a <= 0) { Destroy(gameObject); break; // 루프 탈출 } else { spriteRenderer.color = color; } yield return(null); } } }
private void Finding() { waitTime -= Time.deltaTime; if (waitTime < 0) { // 쓰레기 찾기 //var scrapManager = FindObjectOfType<ScrapManager>(); var trashes = scrapManager.FindTrashes(); if (trashes.Length > 0) { // 가장 가까운 쓰레기 찾기 Transform nearTransform = null; float nearSqrDistance = float.MaxValue; foreach (var trash in trashes) { var trashTransform = trash.transform; var trashSqrDistance = (trashTransform.position - this.transform.position).sqrMagnitude; if (trashTransform.position.sqrMagnitude < nearSqrDistance) { nearTransform = trashTransform; nearSqrDistance = trashSqrDistance; } } SetTarget(nearTransform); state = AiState.ToLostArticle; } else { // 1초후 재탐색 waitTime = 1; } } }
public VictimMan(MegaTile ParentMegaTile, Animation GroundAnimation, Animation StumpAnimation, Animation ExplodeAnimation, Animation TornadoAnimation, string SoundFileName, Vector2 Position) { this.megatile = ParentMegaTile; this.GroundAnimation = GroundAnimation; this.StumpAnimation = StumpAnimation; this.ExplodeAnimation = ExplodeAnimation; this.TornadoAnimation = TornadoAnimation; this.soundHit = SoundFileName; GroundHealth = 100; TornadoHealth = 200; Mass = 200; bounds = new Rectangle2D(Position.X, Position.Y, GroundAnimation.FrameWidth, GroundAnimation.FrameHeight); state = State.Ground; aiState = AiState.Idle; PreLoadSounds(); }
private void Cleaning() { if (targetObject == null) { state = AiState.Finding; } }
public AiState.pirateState chooseState(AiState.pirateState state) { switch (state) { case AiState.pirateState.idle: { if (blocked) return AiState.pirateState.blocked; if (canThrowing) return AiState.pirateState.throwing; if (canAttack) return AiState.pirateState.attack; if (canChasing) return AiState.pirateState.chasing; if (typePirate != AiState.pirate.verySober) return AiState.pirateState.wandering; return AiState.pirateState.idle; } case AiState.pirateState.wandering: { if (blocked) return AiState.pirateState.blocked; if (canAttack) return AiState.pirateState.attack; if (canChasing) return AiState.pirateState.chasing; return AiState.pirateState.wandering; } case AiState.pirateState.chasing: { if (blocked) return AiState.pirateState.blocked; if (canAttack) return AiState.pirateState.attack; if (canChasing) return AiState.pirateState.chasing; return AiState.pirateState.wandering; } case AiState.pirateState.attack: { if (blocked) return AiState.pirateState.blocked; if (canAttack) return AiState.pirateState.attack; if (canChasing) return AiState.pirateState.chasing; return AiState.pirateState.idle; } case AiState.pirateState.blocked: { return AiState.pirateState.confuse; } case AiState.pirateState.throwing: { if (blocked) return AiState.pirateState.blocked; return AiState.pirateState.idle; } case AiState.pirateState.confuse: { return AiState.pirateState.idle; } default: Debug.LogError("There is an error in chooseState, invalid state"); return AiState.pirateState.idle; } }
public void choosePirateLife(AiState.pirate pirate) { switch (pirate) { case AiState.pirate.drunk: lifePirate = 1; break; case AiState.pirate.sober: lifePirate = 2; break; case AiState.pirate.verySober: lifePirate = 3; break; default: Debug.LogError("An error in AI choosePirateLifeState"); break; } }
public override void Tick() { base.Tick(); switch (state) { case AiState.Idle: if (GetVisibleActors().Any(a => a is TestAlien)) state = AiState.PanicStart; break; case AiState.PanicStart: var button = m.GetRoomAt(Position.ToSquare()) .Actors.OfType<Alarm>().ClosestTo(this); if (button != null) { state = AiState.PanicGoForButton; SetOrders(PlanPathTo(button.Position.ToSquare()) .Concat( Orders.Face(button.Direction, 1), Orders.Use(button), SetState(AiState.PanicReplan))); } else state = AiState.PanicReplan; break; case AiState.PanicGoForButton: case AiState.PanicRun: break; // todo: if we see something (an alien!) that freaks us out more, replan case AiState.PanicReplan: state = AiState.PanicRun; var dest = m.GetRoomAt(Position.ToSquare()) .ChooseRandomTile(); SetOrders(PlanPathTo(dest) .Concat(SetState(AiState.PanicReplan))); break; } }
void Update() { switch (aiState) { case AiState.Respawned: { JumpUp(); aiState = AiState.FollowingPlayer; break; } case AiState.FollowingPlayer: { var directionToPlayer = GetDirectionToPlayer(); FollowPlayer(directionToPlayer); if (random.Next(0, 1500) == 1000) { aiState = AiState.RandomJump; } if (cachedTransform.position.y < 0.3f) { aiState = AiState.IsFallingDown; } break; } case AiState.IsFallingDown: { JumpUp(); aiState = AiState.FollowingPlayer; break; } case AiState.RandomJump: { RandomJump(); aiState = AiState.FollowingPlayer; break; } } t++; }
public AiScript() { this.Phrases = new List<string>(); _lastBeat = DateTime.MinValue; _heartbeat = IdleHeartbeat; _heartbeatTimer = new Timer(this.Heartbeat, null, -1, -1); _rnd = new Random(RandomProvider.Get().Next()); _state = AiState.Idle; _aggroRadius = 500; _aggroMaxRadius = 3000; _alertDelay = TimeSpan.FromMilliseconds(8000); _aggroDelay = TimeSpan.FromMilliseconds(4000); _hateTags = new Dictionary<string, string>(); _loveTags = new Dictionary<string, string>(); _aggroType = AggroType.Passive; _aggroLimit = AggroLimit.One; }
public override void Update(float Time) { switch (state) { case State.Ground: switch (aiState) { case AiState.Panic: GroundAnimation.Update(Time); Move(Time); break; case AiState.Running: GroundAnimation.Update(Time); Move(Time); break; case AiState.Idle: if (megatile.level.Tornado != null) { float distanceFromEdgeOfTornado = (megatile.level.Tornado.Position - this.bounds.Center).Length(); if (distanceFromEdgeOfTornado < this.megatile.level.Tornado.Radius + 32*Math.Sqrt(this.megatile.level.Tornado.Radius)) //Distance we can see the tornado { aiState = AiState.Running; } } break; } break; case State.Flying: TornadoAnimation.Update(Time); drawAngle += 0.05f + Time * timeScaleFactor * updateErrorAngle(0.1f, 0.3f); if (drawAngle > 2 * Math.PI) { drawAngle = 0; } Move(Time); //Performs vector math to circle around tornado break; case State.Exploding: ExplodeAnimation.Update(Time); explodeWait += Time; if (explodeWait > staytime) { requestRemoveTornado = true; } break; case State.Stump: StumpAnimation.Update(Time); break; } }
/// <summary> /// Clears action, target, and sets state to Idle. /// </summary> private void Reset() { this.Clear(); _state = AiState.Idle; if (this.Creature.IsInBattleStance) this.Creature.IsInBattleStance = false; if (this.Creature.Target != null) { this.Creature.Target = null; Send.SetCombatTarget(this.Creature, 0, 0); } }
/// <summary> /// Changes state based on (potential) targets. /// </summary> private void SelectState() { var potentialTargets = this.Creature.Region.GetVisibleCreaturesInRange(this.Creature, _aggroRadius); // Stay in idle if there's no visible creature in aggro range if (potentialTargets.Count == 0 && this.Creature.Target == null) { if (_state != AiState.Idle) this.Reset(); return; } // Find a new target if (this.Creature.Target == null) { // Get hated targets var hated = potentialTargets.Where(cr => this.DoesHate(cr) && !cr.Has(CreatureStates.NamedNpc)); var hatedCount = hated.Count(); // Get doubted targets var doubted = potentialTargets.Where(cr => this.DoesDoubt(cr) && !cr.Has(CreatureStates.NamedNpc)); var doubtedCount = doubted.Count(); // Get loved targets var loved = potentialTargets.Where(cr => this.DoesLove(cr)); var lovedCount = loved.Count(); // Handle hate and doubt if (hatedCount != 0 || doubtedCount != 0) { // Try to hate first, then doubt if (hatedCount != 0) this.Creature.Target = hated.ElementAt(this.Random(hatedCount)); else this.Creature.Target = doubted.ElementAt(this.Random(doubtedCount)); // Switch to aware _state = AiState.Aware; _awareTime = DateTime.Now; } // Handle love else if (lovedCount != 0) { this.Creature.Target = loved.ElementAt(this.Random(lovedCount)); _state = AiState.Love; } // Stop if no targets were found else return; // Stop for this tick, the aware delay needs a moment anyway return; } // TODO: Monsters switch targets under certain circumstances, // e.g. a wolf will aggro a player, even if it has already // noticed a cow. // Reset on... if (this.Creature.Target.IsDead // target dead || !this.Creature.GetPosition().InRange(this.Creature.Target.GetPosition(), _aggroMaxRadius) // out of aggro range || this.Creature.Target.Client.State == ClientState.Dead // target disconnected || (_state != AiState.Aggro && this.Creature.Target.Conditions.Has(ConditionsA.Invisible)) // target hid before reaching aggro state ) { this.Reset(); return; } // Switch to alert from aware after the delay if (_state == AiState.Aware && DateTime.Now >= _awareTime + _alertDelay) { // Check if target is still in immediate range if (this.Creature.GetPosition().InRange(this.Creature.Target.GetPosition(), _aggroRadius)) { this.Clear(); _state = AiState.Alert; _alertTime = DateTime.Now; this.Creature.IsInBattleStance = true; Send.SetCombatTarget(this.Creature, this.Creature.Target.EntityId, TargetMode.Alert); } // Reset if target ran away like a coward. else { this.Reset(); return; } } // Switch to aggro from alert if (_state == AiState.Alert && (this.DoesHate(this.Creature.Target) || (_hatesBattleStance && this.Creature.Target.IsInBattleStance))) { // Check aggro limit var aggroCount = this.Creature.Region.CountAggro(this.Creature.Target, this.Creature.RaceId); if (aggroCount >= (int)_aggroLimit) return; this.Clear(); _state = AiState.Aggro; Send.SetCombatTarget(this.Creature, this.Creature.Target.EntityId, TargetMode.Aggro); } }
protected void ChangeState (AiState state, System.Action initFunc) { List<AiState> can; if (transitable.TryGetValue (currentState, out can) == false) { throw new UnityException ("cannot find transitable list"); } if (can.FindIndex (s => s == state) != -1) { if (currentState != state) { System.Action stateEndFunc; if (stateEnd.TryGetValue (currentState, out stateEndFunc) == false) { stateEndFunc = null; } if (stateEndFunc != null) { stateEndFunc (); } if (initFunc != null) initFunc (); System.Action stateStartFunc; if (stateStart.TryGetValue (state, out stateStartFunc) == false) { stateStartFunc = null; } if (stateStartFunc != null) { stateStartFunc (); } if (stateMachine.TryGetValue (state, out currentStateAction) == false) { currentStateAction = null; } } else { if (initFunc != null) initFunc (); } currentState = state; nextState = null; } }
/// <summary> /// Sets target and puts creature in battle mode. /// </summary> /// <param name="creature"></param> protected void AggroCreature(Creature creature) { _state = AiState.Aggro; this.Creature.BattleStance = BattleStance.Ready; this.Creature.Target = creature; Send.SetCombatTarget(this.Creature, this.Creature.Target.EntityId, TargetMode.Aggro); }
/// <summary> /// Changes state based on (potential) targets. /// </summary> private void SelectState() { // Always goes back into idle if there's no target. // Continue if neutral has a target, for the reset checks. if (_aggroType == AggroType.Passive && this.Creature.Target == null) { _state = AiState.Idle; return; } // Find a target if you don't have one. if (this.Creature.Target == null) { // Try to find a target this.Creature.Target = this.SelectRandomTarget(this.Creature.Region.GetVisibleCreaturesInRange(this.Creature, _aggroRadius)); if (this.Creature.Target != null) { _state = AiState.Aware; _awareTime = DateTime.Now; } } // Got target. else { // Untarget on death, out of range, or disconnect if (this.Creature.Target.IsDead || !this.Creature.GetPosition().InRange(this.Creature.Target.GetPosition(), _aggroMaxRadius) || this.Creature.Target.Client.State == ClientState.Dead || (_state != AiState.Aggro && this.Creature.Target.Conditions.Has(ConditionsA.Invisible))) { this.Reset(); return; } // Switch to alert from aware after the delay if (_state == AiState.Aware && DateTime.Now >= _awareTime + _alertDelay) { // Check if target is still in range if (this.Creature.GetPosition().InRange(this.Creature.Target.GetPosition(), _aggroRadius)) { this.Clear(); _state = AiState.Alert; _alertTime = DateTime.Now; this.Creature.BattleStance = BattleStance.Ready; Send.SetCombatTarget(this.Creature, this.Creature.Target.EntityId, TargetMode.Alert); } // Reset if target ran away like a coward. else { this.Reset(); } return; } // Switch to aggro from alert after the delay if (_state == AiState.Alert && (_aggroType == AggroType.Aggressive || (_aggroType == AggroType.CarefulAggressive && this.Creature.Target.BattleStance == BattleStance.Ready) || (_aggroType > AggroType.Passive && !this.Creature.Target.IsPlayer)) && DateTime.Now >= _alertTime + _aggroDelay) { // Check aggro limit var aggroCount = this.Creature.Region.CountAggro(this.Creature.Target, this.Creature.Race); if (aggroCount >= (int)_aggroLimit) return; this.Clear(); _state = AiState.Aggro; Send.SetCombatTarget(this.Creature, this.Creature.Target.EntityId, TargetMode.Aggro); return; } } }
public void Panic( Model m ) { state = AiState.PanicStart; }
Order SetState(AiState newState) { return a => { (a as Food).state = newState; return true; }; }
/// <summary> /// Sets target and puts creature in battle mode. /// </summary> /// <param name="creature"></param> public void AggroCreature(Creature creature) { _state = AiState.Aggro; this.Clear(); this.Creature.IsInBattleStance = true; this.Creature.Target = creature; Send.SetCombatTarget(this.Creature, this.Creature.Target.EntityId, TargetMode.Aggro); }
public void changeState(AiState.pirateState newState) { prevState = currentState; currentState = newState; }
public void StartWaypoint(long Tick) { //Log.Info("Waypoints", "Starting Waypoint"); State = AiState.MOVING; _Owner.GetUnit().MvtInterface.WalkTo(CurrentWaypoint.X, CurrentWaypoint.Y, CurrentWaypoint.Z, CurrentWaypoint.Speed); if (!Started) { // TODO : Messages,Emotes, etc if(CurrentWaypoint.TextOnStart != "") _Owner.GetUnit().Say(CurrentWaypoint.TextOnStart, SystemData.ChatLogFilters.CHATLOGFILTERS_MONSTER_SAY); } Started = true; Ended = false; }
protected override void Move(float time) { switch(state) { case State.Ground: switch (aiState) { case AiState.Running: { updateErrorAngle(0.2f, (float)Math.PI / 8); moveAngle = getAngleToPoint(megatile.level.Tornado.Position) + (float)Math.PI + (speed/3.0f) * errorAngle; drawAngle = moveAngle; Rectangle2D tempLocation = this.bounds.Copy(); #region performmove tempLocation.X += (float)(Math.Sin(moveAngle) * (speed)) * time * timeScaleFactor; tempLocation.Y -= (float)(Math.Cos(moveAngle) * (speed)) * time * timeScaleFactor; #endregion #region Do we panic? if (this.megatile.Bounds.IsWithin(tempLocation)) { //we are still within our megatile this.bounds = tempLocation; } else { //go crazy aiState = AiState.Panic; } #endregion } break; case AiState.Panic: { Rectangle2D tempLocation = this.bounds.Copy(); if (!free) { updateErrorAngle(0.2f, (float)Math.PI / 8); moveAngle += errorAngle; drawAngle = moveAngle; } #region performmove tempLocation.X += (float)(Math.Sin(moveAngle) * (speed)) * time * timeScaleFactor; tempLocation.Y -= (float)(Math.Cos(moveAngle) * (speed)) * time * timeScaleFactor; #endregion if (this.megatile.Bounds.IsWithin(tempLocation)) { //we are still within our megatile this.bounds = tempLocation; free = true; } else { free = false; } } break; } break; case State.Flying: aiState = AiState.Panic; updateErrorDist(tornado.Radius / 8, tornado.Radius / 1.5f); //generates a new error term updateErrorSpeed(tornado.RotationalSpeed / 10.0f, tornado.RotationalSpeed / 2); //generates a new error speed term moveAngle = getAngleToPoint(tornado.Position) + (float)Math.PI / (2 * (getDistanceFromTornado() / (tornado.Radius + errorDist))); #region performmove this.bounds.X += (float)(Math.Sin(moveAngle) * (tornado.RotationalSpeed + errorSpeed)) * time * timeScaleFactor; this.bounds.Y -= (float)(Math.Cos(moveAngle) * (tornado.RotationalSpeed + errorSpeed)) * time * timeScaleFactor; #endregion #region RubberBand RubberBandMe(time); #endregion break; } }
/// <summary> /// Sets target and puts creature in battle mode. /// </summary> /// <param name="creature"></param> public void AggroCreature(Creature creature, bool alert = false) { _state = alert ? AiState.Alert : AiState.Aggro; this.Clear(); this.Creature.IsInBattleStance = true; this.Creature.Target = creature; Send.SetCombatTarget(this.Creature, this.Creature.Target.EntityId, alert ? TargetMode.Alert : TargetMode.Aggro); }
/// <summary> /// Reigsters a reaction. /// </summary> /// <param name="ev">The event on which func should be executed.</param> /// <param name="func">The reaction to the event.</param> protected void On(AiState state, AiEvent ev, Func<IEnumerable> func) { lock (_reactions) _reactions[state][ev] = func; }
public virtual void AI2() { Vector2 dir = _target.position - transform.position; float mag = dir.magnitude; //Is the target in range? if(mag < _aggroRange) { LayerMask mask = (1 << 8); //LayerMask mask = ~(1 << 9); //Is there a wall hiding the target //RaycastHit2D hit = Physics2D.Raycast(transform.position,dir,mag,mask); //Debug.Log (hit.transform.name); // Debug.DrawRay(transform.position,dir); //int numberhits = Physics2D.RaycastNonAlloc(transform.position,dir,_rayHits,Mathf.Sqrt(mag)); //Debug.Log (numberhits.ToString()+" - "+transform.name); //if(numberhits > 1) if(Physics2D.Raycast(transform.position,dir,mag,mask)) { //hitstuff = hit.transform; //Debug.Log (hit.transform.name + this.name + _hasSeen.ToString ()); //If you've seen him before, go there, else do nothing if(_hasSeen) { Vector3 newdir = _lastSeen - transform.position; float newmag = newdir.magnitude; //If you're where you last saw him, forget about it if(newmag < 1.5) { _hasSeen = false; H_ObjectState = ObjectState.Idle; _aiState = AiState.Idle; } else { ResetAttackState(); H_ObjectState = ObjectState.Walking; H_objectDirection = newdir; rigidbody2D.velocity = H_objectDirection * 2; _aiState = AiState.Approach; } } else { //do nothing H_ObjectState = ObjectState.Idle; _aiState = AiState.Idle; } } else { _lastSeen = _target.position; _hasSeen = true; //If close enough, Attack, else, move closer if(mag < _attackRange) { rigidbody2D.velocity = Vector2.zero; if( H_ObjectState != ObjectState.Attacking && H_ObjectState != ObjectState.Smashing){ PerformAttacks(); } _attackCooldownCur = _attackCooldownMax; _aiState = AiState.Combat; } else { ResetAttackState(); H_ObjectState = ObjectState.Walking; H_objectDirection = dir; rigidbody2D.velocity = H_objectDirection * 2; _aiState = AiState.Approach; } } } else { //do nothing H_ObjectState = ObjectState.Idle; _aiState = AiState.Idle; } }
public virtual void AI() { Vector2 dir = _target.position - transform.position; float mag = dir.magnitude; switch (_aiState) { case AiState.Idle: if(mag < _aggroRange) { _aiState = AiState.Approach; H_ObjectState = ObjectState.Walking; } break; case AiState.Patrol: break; case AiState.Approach: if(mag < _fightMinRange) { //Attack him!! //H_ObjectState = ObjectState.Walking; //rigidbody2D.velocity = Vector2.zero; _aiState = AiState.Combat; } else if(mag < _loseAggroRange) { H_ObjectState = ObjectState.Walking; H_objectDirection = dir; rigidbody2D.velocity = H_objectDirection * 5; } else { _aiState = AiState.Idle; rigidbody2D.velocity = Vector2.zero; H_ObjectState = ObjectState.Idle; } break; case AiState.Combat: if(mag > _fightMaxRange) { _aiState = AiState.Approach; H_ObjectState = ObjectState.Walking; } //else if(_attackCooldownCur < 0) { if(mag < _attackRange) { rigidbody2D.velocity = Vector2.zero; if( H_ObjectState != ObjectState.Attacking && H_ObjectState != ObjectState.Smashing){ PerformAttacks(); } _attackCooldownCur = _attackCooldownMax; } else { ResetAttackState(); H_ObjectState = ObjectState.Walking; H_objectDirection = dir; rigidbody2D.velocity = H_objectDirection * 2; } } /*else { _attackCooldownCur -= Time.deltaTime; H_ObjectState = ObjectState.Blocking; if(mag < _safeDistanceCooldown) { H_objectDirection = dir; rigidbody2D.velocity = H_objectDirection * -2; } else if(mag > _fightMinRange) { H_objectDirection = dir; rigidbody2D.velocity = H_objectDirection * 2; } else { rigidbody2D.velocity = Vector2.zero; } }*/ break; default: break; } }
private void SetState(AiState state, float duration) { _state = state; _timer.Set(duration); }
public void CombatStop() { //Log.Success("CombatStop", Obj.Name + " Stop combat "); State = AiState.STANDING; ClearTargets(); if (Obj.IsCreature()) Obj.GetCreature().MvtInterface.StopFollow(); if(Obj.IsCreature() && !Obj.GetCreature().IsDead) ReturnToSpawn(); Obj.EvtInterface.Notify("CombatStop", null, null); }
public override void Update(GameTime gameTime) { if (IsDead) return; speedMultiplier = 1.0f; newPos = Position; dirX = 0; dirY = 0; if (attackCoolDownTicks > 0) attackCoolDownTicks--; Player player = this.ScanForPlayer(); if (!(player == null)) { aiState = AiState.TARGETTING; if (DistanceTo(this, player) < attackRange) { aiState = AiState.ATTACKING; } var angle = Math.Atan2(player.Position.Y - Position.Y, player.Position.X - pos.X); if (angle > MathHelper.PiOver4 && angle < MathHelper.PiOver4 * 3) direction = 1; else if (angle < -MathHelper.PiOver4 && angle > -MathHelper.PiOver4 * 3) direction = 0; else if (angle < MathHelper.PiOver4 && angle > -MathHelper.PiOver4) direction = 3; else if (angle > MathHelper.PiOver4 * 3 && angle < MathHelper.PiOver4 * 5) direction = 2; } else { aiState = AiState.ROAMING; } switch (aiState) { case AiState.ROAMING: // If the player has not been found, move randomly { Roam(); break; } case AiState.TARGETTING: // If the player HAS been found, move torwards it and sprint { isMoving = true; speedMultiplier *= 1.085f; var firstPoint = GetTargetDirection(player); dirX = (int)(firstPoint.X - (int)Math.Round(Position.X / (double)32) * 32); dirY = (int)(firstPoint.Y - (int)Math.Round(Position.Y / (double)32) * 32); var to = new Vector2(dirX, dirY); to.Normalize(); newPos = Position + to; break; } case AiState.ATTACKING: // Attack the player. Attacking prevents moving { isMoving = false; Attack(player as Entity); return; } } Move(newPos); }
public override void Update(GameTime gameTime) { newPos = Position; dirX = 0; dirY = 0; Player player = this.ScanForPlayer(); if (!(player == null)) { aiState = AiState.TARGETTING; if (Vector2.Distance(Position, player.Position) < detectRange / 4) { aiState = AiState.ATTACKING; } var angle = Math.Atan2(player.Position.Y - Position.Y, player.Position.X - pos.X); if (angle > MathHelper.PiOver4 && angle < MathHelper.PiOver4 * 3) dir = 1; else if (angle < -MathHelper.PiOver4 && angle > -MathHelper.PiOver4 * 3) dir = 0; else if (angle < MathHelper.PiOver4 && angle > -MathHelper.PiOver4) dir = 3; else if (angle > MathHelper.PiOver4 * 3 && angle < MathHelper.PiOver4 * 5) dir = 2; } else { aiState = AiState.ROAMING; } switch (aiState) { case AiState.ROAMING: // If the player has not been found, move randomly { Roam(); break; } case AiState.TARGETTING: // If the player HAS been found, move torwards it and sprint { isMoving = true; Vector2 direction = determineMoveDirection(player); var newDir = direction - Position; newDir.Normalize(); newPos = Position + newDir * 2; break; } case AiState.ATTACKING: // Attack the player. Attacking prevents moving { isMoving = false; return; } } Move(newPos.X, newPos.Y); }
public void CombatStart(Unit Fighter) { Log.Success("CombatStart", Obj.Name + " Start combat with " + Fighter.Name); State = AiState.FIGHTING; GetAggro(Fighter.Oid).DamagesReceive+=100; }
public void UpdateWaypoints(long Tick) { if (State == AiState.STANDING || State == AiState.MOVING) { if (Waypoints.Count == 0) return; if (CurrentWaypoint != null && IsAtWaypointEnd()) EndWaypoint(Tick); if (CanStartNextWaypoint(Tick)) SetNextWaypoint(Tick); if (State == AiState.MOVING && Mvt.CurrentSpeed == 0) State = AiState.STANDING; if (State == AiState.STANDING && CurrentWaypoint != null) { StartWaypoint(Tick); } } }
protected AiScript() { this.Phrases = new List<string>(); _lastBeat = DateTime.MinValue; _heartbeat = IdleHeartbeat; _heartbeatTimer = new Timer(this.Heartbeat, null, -1, -1); _rnd = new Random(RandomProvider.Get().Next()); _reactions = new Dictionary<AiState, Dictionary<AiEvent, Func<IEnumerable>>>(); _reactions[AiState.Idle] = new Dictionary<AiEvent, Func<IEnumerable>>(); _reactions[AiState.Aware] = new Dictionary<AiEvent, Func<IEnumerable>>(); _reactions[AiState.Alert] = new Dictionary<AiEvent, Func<IEnumerable>>(); _reactions[AiState.Aggro] = new Dictionary<AiEvent, Func<IEnumerable>>(); _reactions[AiState.Love] = new Dictionary<AiEvent, Func<IEnumerable>>(); _state = AiState.Idle; _aggroRadius = 500; _aggroMaxRadius = 3000; _alertDelay = TimeSpan.FromMilliseconds(8000); _hateTags = new Dictionary<string, string>(); _loveTags = new Dictionary<string, string>(); _doubtTags = new Dictionary<string, string>(); _maxDistanceFromSpawn = 3000; _aggroLimit = AggroLimit.One; }
protected void RequestChangeState (AiState state, System.Action initFunc = null) { nextState = state; nextStateInitAction = initFunc; }