- Home /
How to change enemy's Direction on FiniteStateMachine???
Hello coders.. just a quick question to make: I have a small terrain with a character that is moving on it(user input- keyboard&mouse), and i also have a enemy object that has a Finite state machine. However, I think the State Machine is working fine from IDLE to PATROL and back.
public enum State { IDLE, PATROL, CHASE} //ALL STATES IN ENUM
public State myState; //ONE STATE
private bool alive;
public GameObject[] wayPoints;
private int wayPointIndex = 0; //Store the current index of waypoints
void Start()
{
StartCoroutine("FiniteStateMachine"); //Call State Machine
}
IEnumerator FiniteStateMachine()
{
//While the tiger is alive do switch statement for the State Machine
while (alive)
{
switch (myState)
{
case State.IDLE:
Idle(); //Tiger Is not Moving
break;
case State.PATROL:
Patrol(); //Tiger Is Moving from Waypoint to Waypoint
break;
case State.CHASE:
Chase(); //Tiger Is Chasing the Character
break;
}
yield return null;
} //End of While Loop
How should i change the Enemy's direction when the States are changing since it has a different direction for wayPoints and different direction for the target using Vector 3 for both cases.
private Vector3 wayPointDirection; //Use for the Way Points (PATROL State)
private Vector3 targetDirection; //Use for the target (CHASE State)
If you have a question ill be happy to answer asap. and i will really appreciate it if you guys will help me out fix this issue. :))
Answer by Buckslice · Nov 30, 2017 at 08:37 PM
I'm not sure how your tiger's movement is setup but if you have something like a current direction variable you can just set currentDir = wayPointDir
every frame in the Patrol() function and currentDir = targetDirection
every frame in the Chase() function. Then use that variable in your movement code.
If you want to smoothly change direction and not have it snap instantly upon state switch you could use something like this
// patrol example
currentDir = Vector3.Lerp(currentDir, wayPointDir, Time.deltaTime * 2.0f);
Hello Buckslice, thanks for your feedback its working great. Let me know if you recommend a more efficient way of doing it.
//$$anonymous$$ove to Target
targetDirection = target.transform.position - transform.position;
currentDirection = targetDirection; //Set current direction to the target
//Rotate Target
this.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(currentDirection), tigerWalkSpeed * Time.deltaTime);
this.transform.Translate(0, 0, tigerRunSpeed * Time.deltaTime);
Your answer
Follow this Question
Related Questions
Have Ghost go from Patrolling to Chasing - Pacman 0 Answers
AI will complete patrolling and wait for 5 seconds 2 Answers
NPC won't move after adding chase code. 1 Answer
AI faces Weird Direction when following a waypoint 0 Answers
City traffic Lanes 3 Answers