• 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
1
Question by chinjl · Aug 28, 2017 at 06:03 PM · 2d-platformerenemypathfindingdistancechase

How to make my enemy discover, chase and lose player.

I have been try to find and try the code from google and unity3d.com, but still cannot work, maybe i dun understand.

The code i using now is

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class GuardMovement : MonoBehaviour 
 {
     //public float speed;
     Rigidbody2D rb;
     private Animator animator;
 
     protected Vector3 velocity;
     public Transform _transform;
     public float distance = 5f;
     public float speed = 1f;
     Vector3 _originalPosition;
     bool isGoingLeft = false;
     public float distFromStart;
 
     /*private float movespd = 1.0f;
     //private int dir = -1;
     public const float TurnLimit = 3.5f, CheckLimit = 2.0f;
     public bool detect_player = false;
     public bool after_chase = false;
     public bool checkplayerloc = false;
     public bool dirCheck = false;
     public bool chgdir = false;
     public enum State{Patrol, ChasePlayer, ReturnToOriloc};
     public State behaviourState;
     private Rigidbody2D enemy_rb2d;
     private Vector3 oriloc;
     private Vector2 newposition;
     //private float checktime = CheckLimit;
     //turntime = TurnLimit,*/
     private Transform player;
 
     void Start () 
     {
         rb = GetComponent <Rigidbody2D> ();
         animator = t$$anonymous$$s.GetComponent<Animator> ();
 
         _originalPosition = gameObject.transform.position;
         _transform = GetComponent<Transform>();
         velocity = new Vector3(speed,0,0);
         _transform.Translate ( velocity.x*Time.deltaTime,0,0);
 
         player = GameObject.FindGameObjectWithTag ("Player").transform;
 
         //oriloc = transform.position;
         //behaviourState = State.Patrol;
         //enemy_rb2d = gameObject.GetComponent<Rigidbody2D> ();
 
     }
 
     void Update () 
     {
         distFromStart = transform.position.x - _originalPosition.x;  
 
         if (isGoingLeft) 
         { 
             // If gone too far, switch direction
             if (distFromStart < -distance)
                 SwitchDirection ();
 
             _transform.Translate (-velocity.x * Time.deltaTime, 0, 0);
 
             if (distFromStart < 3) 
             {
                 animator.SetInteger ("Direction", 3);
             }
         } 
         else 
         {
             // If gone too far, switch direction
             if (distFromStart > distance)
                 SwitchDirection ();
 
             _transform.Translate (velocity.x * Time.deltaTime, 0, 0);
 
             if (distFromStart > -3) 
             {
                 animator.SetInteger ("Direction", 1);
             }
         }
 
     }
 
     void SwitchDirection()
     {
         isGoingLeft = !isGoingLeft;
         //TODO: Change facing direction, animation, etc
     }
 }
 

How do i put the code inside my code that the enemy have chase my character in a certain distance, after that distance enemy will go back to it own certain area continuous walk around in that area.

Comment
Add comment · Show 2
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 Cherno · Aug 28, 2017 at 11:38 PM 0
Share
avatar image chinjl · Aug 29, 2017 at 02:20 PM 0
Share

2 Replies

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

Answer by BlackHack_ · Aug 29, 2017 at 03:19 PM

Sorry my answer wasn't detailed enough because I didn't understand your question clearly. I have rewritten your code with performance and readability in mind, and tried to explain everyt$$anonymous$$ng using comments. Btw <= means less than or equal.

 using UnityEngine;
 
 public class GuardMovement : MonoBehaviour
 {
     public float playerDetectionRange = 50;
     public float playerDeathZone = 1f;
     public float patrolDistance = 5f;
     public float speed = 1f;
     // Using a multiplyer to avoid having another var
     // for walking speed and anothor one for current speed.
     public float runningSpeedMultiplyer = 1.5f;
 
     Animator animator;
 
     // Patroling
     Vector3[] patrolPositions;
     int patrolPositionsIndex;
 
     Vector3 startPosition;
     Vector3 targetPosition;
     Transform player;
     bool isTargetingPlayer = false;
 
     void Start()
     {
         animator = GetComponent<Animator>();
 
         startPosition = transform.position;
 
         patrolPositions = new Vector3[] {
             new Vector3(startPosition.x + patrolDistance, startPosition.y, startPosition.z),
             new Vector3(startPosition.x - patrolDistance, startPosition.y, startPosition.z)
         };
 
         // To save preformance if your game has only 1 player,
         // then change it in the declearation to be:
         // static Transform player;
         // and add that here:
         // if (player == null)    
         player = GameObject.FindGameObjectWithTag("Player").transform;
     }
 
     void Update()
     {
         if (IsPlayerInDetectionRange())
         {
             // The player is moving so we need to update the every frame.
             SetTargetPosition(player.position);
 
             // Will only not target the player w$$anonymous$$le in range
             // once he enters the detection range.
             if (!isTargetingPlayer)
             {
                 isTargetingPlayer = true;
                 OnPlayerEnter();
             }
 
             if (IsPlayerInAttackRange())
             {
                 // Do whatever you want in here to
                 // indicate that the player is dead.
 
                 // player.Kill();
             }
         }
         // If not in range.
         else
         {
             // will only taget the player w$$anonymous$$le not in range
             // once he leaves the detection range.
             if (isTargetingPlayer)
             {
                 isTargetingPlayer = false;
                 OnPlayerLeave();
             }
 
             // Patrol only w$$anonymous$$le no player in range.
             Patrol();
         }
 
         MoveToTargetPosition();
     }
 
     bool IsPlayerInDetectionRange()
     {
         if (Vector2.Distance(transform.position, player.position) < playerDetectionRange)
         {
             return true;
         }
         else
         {
             return false;
         }
     }
 
     bool IsPlayerInAttackRange()
     {
         if (Vector2.Distance(transform.position, player.position) < playerDeathZone)
         {
             return true;
         }
         else
         {
             return false;
         }
     }
 
     void OnPlayerEnter()
     {
         speed *= runningSpeedMultiplyer; // same as (speed = speed * runningSpeedMultiplyer)
     }
 
     void OnPlayerLeave()
     {
         speed /= runningSpeedMultiplyer; // same as (speed = speed / runningSpeedMultiplyer)
     }
 
     void Patrol()
     {
         // Putting it in a var just to make it easier to read.
         Vector3 currentPatrolPosition = patrolPositions[patrolPositionsIndex];
 
         // If we are not patroling (if after chasing a player)
         if (targetPosition != currentPatrolPosition)
         {
             SetTargetPosition(currentPatrolPosition);
         }
 
         // If we have reached our target patrol, then switch to the next one.
         if (transform.position == currentPatrolPosition)
         {
             patrolPositionsIndex++; // same as (patrolPositionsIndex = patrolPositionsIndex + 1)
 
             // We currently have 2 patrol position stored in an array,
             // if the index is bigger than or equal to the length of the array (2),
             // then we will start from the beggining (index 0).
             if (patrolPositionsIndex >= patrolPositions.Length)
                 patrolPositionsIndex = 0;
 
             SetTargetPosition(patrolPositions[patrolPositionsIndex]);
         }
     }
 
     void SetTargetPosition(Vector3 newTargetPosition)
     {
         targetPosition = newTargetPosition;
 
         // if is going left
         if (transform.position.x < targetPosition.x)
         {
             animator.SetInteger("Direction", 3);
         }
         // if is going right
         else
         {
             animator.SetInteger("Direction", 1);
         }
     }
 
     void MoveToTargetPosition()
     {
         transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
     }
 }
Comment
Add comment · Show 3 · 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 chinjl · Aug 29, 2017 at 05:52 PM 0
Share
screenshot-205.jpg (727.6 kB)
avatar image BlackHack_ chinjl · Aug 30, 2017 at 04:33 PM 0
Share
avatar image chinjl · Aug 30, 2017 at 12:21 PM 0
Share
avatar image
0

Answer by donkey0t · Aug 29, 2017 at 05:03 PM

I'm a total newbie so forgive me if I'm talking nonsense, but I'd be looking at using the navigation mesh/path calculations and feed it the point of the players position. Then after a certain time I'd change the target of the path to a fixed point rather than the player?

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 BlackHack_ · Aug 29, 2017 at 10:57 PM 0
Share

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

75 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

Related Questions

can someone look at this script for me 1 Answer

2d c# boss follow code 0 Answers

i have a field of view script how to add enemy chase ai 1 Answer

Enemy follow script without rotation 1 Answer

Enemy raycast chase player 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