Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by CletusKasady · Apr 03, 2018 at 09:59 PM · if-statementsfinite-state-machine

Switching between states of a FSM

Hey all, hope someone can help. I'm working on making a finite state machine in unity for some npc creatures. The most basic one I'm working on now is a creature with only 2 states, wander and standoff. (normal wandering behavior, following waypoints and whatnot and standoff should just stand in place and rotate to face the player when they move too close. I'm very new to C# and unity but the code I have feels like it should work. I'm not very aware of how to implement enumerators and some of the more advanced stuff I keep seeing online so I tried to implement a single monobehavior and start with state = 0. in the update i have a check if the player gets too close and changes state =1. so each state's actions are within the update inside an if(state=0) or if(state=1) except I can't get my npc to enter the standoff state, instead it just keeps wandering around. i copied my code below, any help would be amazing. thanks.

public class Wander : MonoBehaviour { public float turnSensitivityX = 5F; public float moveSensitivity = 5f;

 public float nextway;

 public GameObject[] waypoints;

 Quaternion originalRotation;

 public int previous = -1;
 public Vector3 way;

 public GameObject player;
 public Vector3 playerpos;

 public float proximityThreshold = 15F;

 public int state;

 void Start()
 {
     waypoints = GameObject.FindGameObjectsWithTag("waypoint");
     nextway = Random.Range(0, 5);
     player = GameObject.FindGameObjectWithTag("Player");
     playerpos = player.transform.position;
     state = 0;
 }


 // Update is called once per frame
 void Update()
 {
     if (state == 0) {
         way = waypoints[(int)nextway].transform.position;
         //transform.LookAt(way);

         var threshold = 0;
         Vector3 localTarget = transform.InverseTransformPoint(way);
         if (localTarget.x < -threshold)
         {
             transform.Rotate(0f, -turnSensitivityX * Time.deltaTime, 0f);
         }
         else if (localTarget.x > threshold)
         {
             transform.Rotate(0f, turnSensitivityX * Time.deltaTime, 0f);
         }

         //match the y position to the terrain map
         Vector3 pos = transform.position;
         pos.y = Terrain.activeTerrain.SampleHeight(transform.position);
         pos.y = pos.y + (float)2.0;
         transform.position = pos;

         transform.position += transform.TransformDirection(Vector3.forward) * moveSensitivity * Time.deltaTime;
         if (Mathf.Sqrt(Mathf.Pow(transform.position.x - way.x, 2) + Mathf.Pow(transform.position.z - way.z, 2)) < 5)
         {
             // when the distance between object and the waypoint is less than 5 select a new waypoint target
             nextway = NewWay((int)nextway);
         }
         if (Mathf.Sqrt(Mathf.Pow(transform.position.x - playerpos.x, 2) + Mathf.Pow(transform.position.z - playerpos.z, 2)) < proximityThreshold)
         {
             state = 1;
         }
     }
     if (state == 1)
     {
         //transform.LookAt(playerpos);
         var pthreshold = 0;
         Vector3 target = transform.InverseTransformPoint(playerpos);
         if (target.x < -pthreshold)
         {
             transform.Rotate(0f, -turnSensitivityX * Time.deltaTime, 0f);
         }
         else if (target.x > pthreshold)
         {
             transform.Rotate(0f, turnSensitivityX * Time.deltaTime, 0f);
         }
         if (Mathf.Sqrt(Mathf.Pow(transform.position.x - playerpos.x, 2) + Mathf.Pow(transform.position.z - playerpos.z, 2)) > proximityThreshold)
         {
             state = 0;
         }
     }        
 }

 public int NewWay(int previous) {
     var next = Random.Range(0, 5);
     while (next == previous)
     {
         next = Random.Range(0, 5);
     }
     
     return next;
 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Rygaran · Apr 04, 2018 at 03:33 PM

Your problem is that you take the playerpos at the start and never again, so its always calculatig the distance to the startpoint of the player. This is because vectors are not classes, they are structs. struct are just data types, like ints and bools, they hold the vector data you give them at a point in time, not the reference to the vector in the player.transform. You should read more about data types and reference types, is quite an important feature of oop.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image CletusKasady · Apr 04, 2018 at 04:35 PM 0
Share

Thanks! @Rygaran that was pretty much my issue, just had to reset playerpos as the first line in the update and it's more or less functioning correctly. Appreciate the help!

avatar image
1

Answer by Cornelis-de-Jager · Apr 03, 2018 at 10:03 PM

Hi Not sure what is wrong, to be honest. Looks fine to me. But it could be that the method used for calculating the distance is wrong. Doesn't look like but just in case try:

 // Old way
 if (Mathf.Sqrt(Mathf.Pow(transform.position.x - playerpos.x, 2) + Mathf.Pow(transform.position.z - playerpos.z, 2)) > proximityThreshold)
 
 // new way
 if (Vector3.Distance(transform.position ,playerpos) > proximityThreshold)
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image CletusKasady · Apr 04, 2018 at 02:58 PM 0
Share

Hi! Thanks for the reply @Cornelis-de-Jager ! I've been messing with the code myself and I've been able to get the npc to trigger its standoff state only sometimes when it walks toward the player follow certain waypoints. Trying to debug this the if conditional you cited ought to be the source of the problem, and my thought was the execution time increase with each instance of $$anonymous$$athf and that's causing the issue? I don't know how distance() works could be the same issue?

Also I was solely calculating distance on the x,z plane which makes sense for my waypoints as they are deep beneath the terrain and that works fine but calculating raw distance to the player makes better sense here anyways.

I just tried you're suggestion out though and got similar results as before, only partially successful at recognizing when the player is too close. Not sure whats causing npc to ignore the distance checks.

avatar image
0

Answer by CletusKasady · Apr 04, 2018 at 10:09 PM

For anyone looking at this thread, here's my updated code with the corrections. The NPC cycles in and out of its state no problem. The NPC rotation is done to be a gradual turn rate but once its facing directly at its target it gets all jittery. been trying to fix that up but not much luck yet.

public class Wander : MonoBehaviour { public float turnSensitivityY = 40F; public float moveSensitivity = 5f; public float nextway; public GameObject[] waypoints; public int previous = -1; public Vector3 way; public GameObject player; public Vector3 playerpos; public float proximityThreshold = 30F; public int state;

 void Start()
 {
     waypoints = GameObject.FindGameObjectsWithTag("waypoint");
     nextway = Random.Range(0, 5);
     player = GameObject.FindGameObjectWithTag("Player");
     playerpos = player.transform.position;
     state = 0;
 }


 // Update is called once per frame
 void Update()
 {
     playerpos = player.transform.position;
     if (state == 0) {

         //if (Mathf.Abs(Mathf.Sqrt((transform.position.x - playerpos.x) * (transform.position.x - playerpos.x) + (transform.position.z - playerpos.z) * (transform.position.z - playerpos.z))) <= proximityThreshold)
         if (Vector3.Distance(transform.position, playerpos) > proximityThreshold)
         {
             state = 1;
         }

         way = waypoints[(int)nextway].transform.position;
         //transform.LookAt(way);

         Vector3 localTarget = transform.InverseTransformPoint(way);
         if (localTarget.x < turnSensitivityY)
         {
             transform.Rotate(0f, -turnSensitivityY * Time.deltaTime, 0f);
         }
         else if (localTarget.x > turnSensitivityY)
         {
             transform.Rotate(0f, turnSensitivityY * Time.deltaTime, 0f);
         }
         else if (localTarget.x < 0)
         {
             transform.Rotate(0f, localTarget.x, 0f);
         }
         else if (localTarget.x > 0)
         {
             transform.Rotate(0f, -localTarget.x, 0f);
         }


         //match the y position to the terrain map
         Vector3 pos = transform.position;
         pos.y = Terrain.activeTerrain.SampleHeight(transform.position);
         pos.y = pos.y + (float)2.0;
         transform.position = pos;

         transform.position += transform.TransformDirection(Vector3.forward) * moveSensitivity * Time.deltaTime;
         if (Mathf.Abs(Mathf.Sqrt((transform.position.x - way.x)*(transform.position.x - way.x) + 
             (transform.position.z - way.z)*(transform.position.z - way.z))) <= 10)
         {
             // when the distance between object and the waypoint is less than 5 select a new waypoint target
             nextway = NewWay((int)nextway);
         }   
     }


     else if (state == 1)
     {
         //transform.LookAt(playerpos);
         //if (Mathf.Abs(Mathf.Sqrt((transform.position.x - playerpos.x) * (transform.position.x - playerpos.x) + (transform.position.z - playerpos.z) * (transform.position.z - playerpos.z))) > proximityThreshold)
         if (Vector3.Distance(transform.position, playerpos) > proximityThreshold)
         {
             state = 0;
         }

         playerpos = player.transform.position;
         Vector3 target = transform.InverseTransformPoint(playerpos);
         if (target.x < turnSensitivityY*Time.deltaTime)
         {
             transform.Rotate(0f, -turnSensitivityY * Time.deltaTime, 0f);
         }

         else if (target.x > turnSensitivityY*Time.deltaTime)
         {
             transform.Rotate(0f, turnSensitivityY * Time.deltaTime, 0f);
         }
         else if (target.x < 0)
         {
             transform.Rotate(0f, target.x, 0f);
         }

         else if (target.x > 0)
         {
             transform.Rotate(0f, -target.x, 0f);
         }
         else if (target.x == 0)
         {
             transform.Translate(0, 0, 0);
         }

     }        
 }

 public int NewWay(int previous) {
     var next = Random.Range(0, 5);
     while (next == previous)
     {
         next = Random.Range(0, 5);
     }
     
     return next;
 }

}

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

77 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Tips on how to handle multiple if statemens 1 Answer

FSM: loading newScene before accesing newState 0 Answers

Different Explosion for Different Collisions 3 Answers

Problem with Counting Collisions 2 Answers

contacts.normal question 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges