#finite state machine
1 messages · Page 1 of 1 (latest)
Code but would be nice to have a list or an array in the inspector to add or remove states for each enemy
What i have now
.
├── BaseAIController.controller
├── EnemyBaseState.cs
├── Enemy.cs
└── StateScripts
├── EnemyAttackState.cs
├── EnemyReturnToOriginState.cs
├── EnemyRunToPlayerState.cs
└── EnemyWanderState.cs
Is this the gameobject/component hierarchy?
This is in my Scripts/Enemy folder
With pure code and states set up like this, the simplest solution is to create a specific enemy controller for each enemy type and have it manage adding the states to the FSM in an initialize call, which is something I've done before.
Do you have an example on how thats done ?
Not off hand. Before I give a high level example, the are classes in StateScripts monobehaviours/scriptable objects or standard C# classes?
EnemyRunToPlayerState
using UnityEngine;
public class EnemyRunToPlayerState : EnemyBaseState
{
public override void OnCollisionEnter(Enemy enemy, Collider2D collider)
{
// throw new System.NotImplementedException();
}
public override void OnDrawGizmosSelected(Enemy e)
{
// throw new System.NotImplementedException();
}
public override void UpdateState(Enemy enemy)
{
GameObject detectedObject;
Debug.Log("Detected objs" + enemy.detectedObjs.Count);
if (enemy.detectedObjs.Count == 0){
Debug.Log("go to wander");
enemy.SwitchState(enemy.wanderState);
return;
}
detectedObject = enemy.detectedObjs[0].gameObject;
if (detectedObject == null || enemy.detectedObjs.Count == 0)
{
enemy.SwitchState(enemy.wanderState);
}
else if (detectedObject != null || enemy.detectedObjs.Count > 0)
{
enemy.transform.position = Vector2.MoveTowards(enemy.transform.position, detectedObject.transform.position, enemy.enemyAsset.speed * Time.deltaTime);
float distance = Vector2.Distance(enemy.transform.position, detectedObject.transform.position);
if (distance < enemy.enemyAsset.meleeRadius)
{
enemy.SwitchState(enemy.enemyAttackState);
}
}
}
}
From the overrides I assume that it is a monobehaviour?
The EnemyBaseState is an abstract class and the Enemy class has MonoBehaviour