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 /
  • Help Room /
avatar image
0
Question by CristiBala24 · Sep 11, 2016 at 12:11 PM · game development

Help with enemy chase script 2D C#

Hi guys!I made a script "enemy patrol" that works perfectly fine but when i add in the same script the script to chase the player if he gets too close it starts to freak out.Here is the code (c# only):

using UnityEngine; using System.Collections;

public class EnemyAITest : MonoBehaviour {

 public Transform[] patrolpoints;
 int currentPoint;
 public float speed=0.5f;
 public float timestill=2f;
 public float sight=3f;
 Animator anim;
 public float force;


 public GameObject player;
 public Enemy enemy;
 [SerializeField]
 private BoxCollider2D range;
 public float chaseDistance = 0.5f;
 public float curDistance;
 public bool playerInRange;
 [SerializeField]
 public Chase chase;
 [SerializeField]
 public EnemyAI patrol;
 public Transform targetEnemy;
 public Transform targetPlayer;
 public BoxCollider2D playerCollider;

 public bool isChased;

 //public Transform target;

 // Use this for initialization
 void Start () {

     player = GameObject.FindGameObjectWithTag ("Player");
     playerInRange = false;

     anim = GetComponent<Animator> ();
     StartCoroutine ("Patrol");
     anim.SetBool("walking",true);
     Physics2D.queriesStartInColliders = false;
 }

 // Update is called once per frame
 void Update () {

     curDistance = Vector3.Distance (targetPlayer.position, targetEnemy.position);

     if (playerCollider.IsTouching(range))
     {
         playerInRange = true;
     } 
     else 
     {
         playerInRange = false;
     }

     if ((playerInRange) && (curDistance <= chaseDistance)) 
     {
         StopCoroutine ("Patrol");
         isChased = true;
         ChaseCheck (speed);
         //targetEnemy.position += (targetPlayer.position - targetEnemy.position).normalized * speed * Time.deltaTime;

     } 
     if((!playerInRange) && ((targetPlayer.position.x <= (patrolpoints[0].position.x -1)) || (targetPlayer.position.x >= (patrolpoints[1].position.x + 1))))
     { 
         StartCoroutine ("Patrol");
         isChased = false;
     }

     RaycastHit2D hit= Physics2D.Raycast (transform.position, transform.localScale.x * Vector2.right, sight);
     if (hit.collider != null && hit.collider.tag == "Player")
         GetComponent<Rigidbody2D> ().AddForce (Vector3.up*force + (hit.collider.transform.position-transform.position)*force);
 }


 public IEnumerator Patrol()
 {
     while (true) {

         if(transform.position.x== patrolpoints[currentPoint].position.x )
         {
             currentPoint++;
             anim.SetBool("walking",false);
             yield return new WaitForSeconds(timestill);
             anim.SetBool("walking",true);
         }


         if(currentPoint >=patrolpoints.Length)
         {
             currentPoint=0;
         }

         transform.position=Vector2.MoveTowards(transform.position,new Vector2(patrolpoints[currentPoint].position.x,transform.position.y),speed);

         if(transform.position.x> patrolpoints[currentPoint].position.x)
             transform.localScale=new Vector3(-1,1,1);
         else if (transform.position.x< patrolpoints[currentPoint].position.x)
             transform.localScale= Vector3.one;


         yield return null;


     }
         
 }

 public void ChaseCheck (float speed)
 {

     targetEnemy.position += (targetPlayer.position - targetEnemy.position).normalized * speed * 1;
     //targetEnemy.position = Vector2.MoveTowards (targetEnemy.position, new Vector2 (targetPlayer.position.x, targetEnemy.position.y), speed * Time.deltaTime);
     //targetEnemy.Translate(Vector2.MoveTowards(targetEnemy.position, targetPlayer.position,chaseDistance) * speed * Time.deltaTime);

 }

}

Thx for your help :3.

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by ArturoSR · Sep 11, 2016 at 12:47 PM

@CristiBala24 Hello there.

OK, is possible that your issue is in the section where you check the foe distance, try to change it to only this:

 // Instead use it like this
 if (playerInRange && curDistance <= chaseDistance) {
     // Here goes your code
 } else if (curDistance > chaseDistance) {
     // Here, change the playerInRange to false and put the rest of your code.
 }


So, this way you can simplify a little your code and recommend to you to remove the else where you check if it's not touching the player, normally you only campare the first option and when the situation changes, that reset the behavior, it's something like: "I see you, going behind you", but if he is too faraway: "Mmmh!, better return to my patrolling", something like that, cheers.

Comment
Add comment · Show 2 · 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 CristiBala24 · Sep 11, 2016 at 01:06 PM 0
Share

@$$anonymous$$oSR This way the patrol keeps resetting while the player is out of chase range. Hope you can help.Thanks!

avatar image CristiBala24 · Sep 11, 2016 at 02:16 PM 0
Share

@$$anonymous$$oSR thanks for your help but we solved our problem! :)

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

68 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

Related Questions

How to create iOS game app? Can you do that in Unity3D on a Windows computer? 1 Answer

2D RPG Game Management - How Do I Approach It? 0 Answers

Possible to make a desktop digital pet with unity?,Is it possible to make the unity window transparent while game is running? 1 Answer

Why doesn't my game function properly after building it? 0 Answers

Daily challenges in game 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