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 ToastandBananas · Jun 26, 2018 at 12:45 AM · unity 52dmovementsprites

Why is the Enemy's Sprite Flipping When it Sees the Player??

So I have a method that flips an enemies sprite if depending on what direction they're moving. I also have a script that determines if it can see the player. Currently, the enemy sprite faces the correct direction when moving, but as soon as it sees the player, it flips around away from the player. Why is this happening?

Sorry in advance for all of the code...

 [RequireComponent(typeof(Rigidbody2D))]
 [RequireComponent(typeof(Seeker))]
 
 public class EnemyMovement : MonoBehaviour {
 
     // What to chase
     public Transform target;
 
     // How many times each second we will update our path
     public float updateRate = 2f;
 
     // Caching
     private Seeker seeker;
     private Rigidbody2D rb;
 
     // The calculated path
     public Path path;
 
     // The AI's speed per second
     public float speed = 300f;
     public ForceMode2D fMode;
 
     [HideInInspector]
     public bool pathIsEnded = false;
 
     // The max distance from the AI to a waypoint for it to continue to the next waypoint
     public float nextWaypointDistance = 3f;
 
     // The waypoint we are currently moving towards
     private int currentWaypoint = 0;
 
     private bool searchingForPlayer = false;
 
     public bool facingRight = true;
 
     public bool stillSearching = false;
 
     float horizontalVelocity;
 
     float timer = 0f;
 
     float continueSearchingTime = 5f;
 
     Vector3 enemyLocation;
 
     Player player;
     EnemySenses enemySenses;
 
     void Start()
     {
         player = Player.instance;
         enemySenses = EnemySenses.instance;
 
         enemyLocation = transform.localScale;
 
         seeker = GetComponent<Seeker>();
         rb = GetComponent<Rigidbody2D>();
 
         if (target == null)
         {
             if (!searchingForPlayer)
             {
                 searchingForPlayer = true;
                 StartCoroutine(SearchForPlayer());
             }
             return;
         }
 
         // Start a new path to the target position, return the result to the OnPathComplete method
         seeker.StartPath(transform.position, target.position, OnPathComplete);
 
         StartCoroutine(UpdatePath());
     }
 
     void Update()
     {
         Flip();
     }
 
     void FixedUpdate()
     {
 
         if (target != null && player.isDead == true || target != null && enemySenses.CanPlayerBeSeen() == false && stillSearching == false)
         {
             searchingForPlayer = false;
             return;
         }
         else if (target != null && stillSearching == true && enemySenses.CanPlayerBeSeen() == false)
         {
             if (!searchingForPlayer)
             {
                 searchingForPlayer = true;
                 StartCoroutine(SearchForPlayer());
             }
         }
         else if (target == null)
         {
             if (!searchingForPlayer)
             {
                 searchingForPlayer = true;
                 StartCoroutine(SearchForPlayer());
             }
             return;
         }
 
         if (path == null)
             return;
 
         if (currentWaypoint >= path.vectorPath.Count)
         {
             if (pathIsEnded)
                 return;
 
             // Debug.Log("End of path reached.");
             pathIsEnded = true;
             return;
         }
 
         pathIsEnded = false;
 
         // Direction to the next waypoint
         Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
         dir *= speed * Time.fixedDeltaTime;
 
         // Move the AI
         rb.AddForce(dir, fMode);
 
         float dist = Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]);
         if (dist < nextWaypointDistance)
         {
             currentWaypoint++;
             return;
         }
     }
 
     void LateUpdate()
     {
         
     }
 
     void Flip()
     {
         horizontalVelocity = GetComponent<Rigidbody2D>().velocity.x;
 
         if (facingRight == true && horizontalVelocity < 0) // Facing right and moving left
         {
             enemyLocation.x *= -1;
             transform.localScale = enemyLocation;
             facingRight = false;
         }
         else if (facingRight == false && horizontalVelocity > 0) // Facing left and moving right
         {
             enemyLocation.x *= -1;
             transform.localScale = enemyLocation;
             facingRight = true;
         }
     }
 
     IEnumerator SearchForPlayer()
     {
         GameObject searchResult = GameObject.FindGameObjectWithTag("Player");
         if (searchResult == null)
         {
             yield return new WaitForSeconds(0.5f);
             StartCoroutine(SearchForPlayer());
         }
         else if (player.isDead == false)
         {
             target = searchResult.transform;
             searchingForPlayer = false;
             StartCoroutine(UpdatePath());
             yield return false;
         }
     }
 
     IEnumerator UpdatePath()
     {
         if (target == null)
         {
             if (!searchingForPlayer)
             {
                 searchingForPlayer = true;
                 StartCoroutine(SearchForPlayer());
             }
             yield return false;
         }
 
         // Start a new path to the target position, return the result to the OnPathComplete method
         seeker.StartPath(transform.position, target.position, OnPathComplete);
 
         yield return new WaitForSeconds(1f / updateRate);
         StartCoroutine(UpdatePath());
     }
 
     public void OnPathComplete (Path p)
     {
         // Debug.Log("We got a path. Did it have an error? " + p.error);
         if (!p.error)
         {
             path = p;
             currentWaypoint = 0;
         }
     }
 
     IEnumerator OnTriggerExit2D()
     {
         stillSearching = true;
 
         while (timer < continueSearchingTime)
         {
             yield return new WaitForSeconds(1f);
             timer++;
             Debug.Log("Timer: " + timer);
         }
 
         if (timer > continueSearchingTime)
         {
             stillSearching = false;
         }
     }
 
     void OnTriggerEnter2D()
     {
         timer = 0;
         stillSearching = false;
     }
 }
Comment
Add comment · Show 1
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 ToastandBananas · Jun 26, 2018 at 03:47 AM 0
Share

Hmm, so I figured out that the x amount for the enemies location was going up and down rapidly by very small amounts when the player gets close enough. I'm not sure why that's happening, but I just changed the values in my Flip() method slightly to this:

      void Flip()
      {
          horizontalVelocity = GetComponent<Rigidbody2D>().velocity.x;
  
          if (facingRight == true && horizontalVelocity < -0.1) // Facing right and moving left
          {
              enemyLocation.x *= -1;
              transform.localScale = enemyLocation;
              facingRight = false;
          }
          else if (facingRight == false && horizontalVelocity > 0.1) // Facing left and moving right
          {
              enemyLocation.x *= -1;
              transform.localScale = enemyLocation;
              facingRight = true;
          }
      }

Anyone have any ideas why this may be happening? Is it the way I'm applying force to move the enemy?

0 Replies

· Add your reply
  • Sort: 

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

284 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 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 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 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

2D player keeps getting dragged to the left for some reason. 0 Answers

Sprite moving too far/fast 1 Answer

OnCollisionEnter2D not triggering on parent 1 Answer

2D endless scrolling game - Which method is best for moving objects without lags? 2 Answers

Character rotation and move to mouse click point with speed 0 Answers


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