Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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
5
Question by RoguPictur · Jan 01, 2014 at 05:38 PM · follow playerartificial intelligencelook

How to make an AI to follow the player in 2D C#

So I have tried just about everything to find out how to script an AI following script correctly.

What my script is supposed to do: Always look at the Player. What script does: *When the Player is on the leftside of the Enemy my enemy looks left and vice versa. *It moves up along it's local y-as.

 using UnityEngine;
 using System.Collections;
 
 public class AiZ : MonoBehaviour {
     Transform target;
     public float speed = .01f;
 
     
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void FixedUpdate () {
 
 
         target = GameObject.FindWithTag ("Player").transform;
 
         Vector3 forwardAxis = new Vector3 (0, 0, -1);
 
 
 
         
         transform.LookAt (target.position, forwardAxis);
         Debug.DrawLine (transform.position, target.position);
         transform.eulerAngles = new Vector3 (0, 0, -transform.eulerAngles.z);
         transform.position -= transform.TransformDirection (Vector2.up) * speed ;
     }
     
 }
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 lordlycastle · Mar 26, 2015 at 10:51 PM 0
Share

Never call Find function in any of the update functions, it's very resource consu$$anonymous$$g. Call it in start and save the reference in a field.

avatar image dreg_master · Mar 19, 2017 at 08:35 AM 0
Share

Great advise in here thanks

3 Replies

· Add your reply
  • Sort: 
avatar image
5

Answer by sath · Jan 01, 2014 at 06:40 PM

Try this:

 using UnityEngine;
 using System.Collections;
 
 public class AiZ : MonoBehaviour {
 
     public Transform target;//set target from inspector instead of looking in Update
     public float speed = 3f;
 
 
     void Start () {
         
     }
 
     void Update(){
         
         //rotate to look at the player
         transform.LookAt(target.position);
         transform.Rotate(new Vector3(0,-90,0),Space.Self);//correcting the original rotation
         
         
         //move towards the player
         if (Vector3.Distance(transform.position,target.position)>1f){//move if distance from target is greater than 1
             transform.Translate(new Vector3(speed* Time.deltaTime,0,0) );
         }
 
     }
 
 }
Comment
Add comment · Show 10 · 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 RoguPictur · Jan 01, 2014 at 07:25 PM 0
Share

So this works half, now the enemy follows my player but it rotates around all 3 axes, so I put

transform.eulerAngles = new Vector3 (0, 0, -transform.eulerAngles.z);

After //rotate to look at the player

So it would only rotate around the z-axis but then the enemy starts moving along the z-axis. To fix this I changed : //move towards the player enemyTransform.position += enemyTransform.forward speed Time.deltaTime;

 //Into
 enemyTransform.position += enemyTransform.up * speed * Time.deltaTime;`
 
 But then it won't rotate anymore :/
avatar image sath · Jan 01, 2014 at 07:59 PM 0
Share

I test the script in an empty scene with Cube(for enemy & this script on it), a Sphere (tag as Player)and it is working fine. Cube(enemy) rotates on Y axis and always follow & looking at Player(sphere).Is this what you want or am I missing something?

avatar image RoguPictur · Jan 01, 2014 at 08:02 PM 0
Share

I'm working in 2D with a top down view, if I want to rotate an object I need to revolve it around the z-axis

avatar image sath · Jan 01, 2014 at 08:23 PM 0
Share
 using UnityEngine;
 using System.Collections;
  
 public class enemy : $$anonymous$$onoBehaviour {
  
     Transform target;
     Transform enemyTransform;
     public float speed = 3f;
     public float rotationSpeed=3f;
  
  
     void Start () {
       //obtain the game object Transform
        enemyTransform = this.GetComponent<Transform>();
     }
  
     void Update(){
 
        target = GameObject.FindWithTag ("Player").transform;
         Vector3 targetHeading = target.position - transform.position;
          Vector3 targetDirection = targetHeading.normalized;
  
        //rotate to look at the player
 
          transform.rotation = Quaternion.LookRotation(targetDirection); // Converts target direction vector to Quaternion
          transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
         
        //move towards the player
        enemyTransform.position += enemyTransform.forward * speed * Time.deltaTime;
  
     }
  
 }
avatar image RoguPictur · Jan 01, 2014 at 11:17 PM 0
Share
 using UnityEngine;
 using System.Collections;
 
 public class AiZ : $$anonymous$$onoBehaviour {
     
     Transform target;
     Transform enemyTransform;
     public float speed = 3f;
     public float rotationSpeed=10f;
     Vector3 upAxis = new Vector3 (0f, 0f, -1f);
     
     void Start () {
         
     }
     
     void FixedUpdate(){
         
                 target = GameObject.FindWithTag ("Player").transform;
         }
 
     void Update(){
         //rotate to look at the player
 
     transform.LookAt (target.position, upAxis);
         transform.eulerAngles = new Vector3 (0f, 0f, transform.eulerAngles.z);
 
 
 
         //move towards the player
         enemyTransform.position += transform.up * speed * Time.deltaTime;
 
     }
     
 }

This is how far I can go, now the enemy follow my player but only in steps of 90° and the enemy won't go down

Show more comments
avatar image
2

Answer by Judgeking · Mar 11, 2017 at 10:06 AM

LookAt won't work in 2D, it makes the sprite flat towards the camera and invisible.

Here's a simple script I wrote:

     private GameObject Player;
 
     void Start () {
         Player = GameObject.Find("Player");
     }
     
     void Update () {
         transform.position = Vector2.MoveTowards(transform.position,Player.transform.position, speed*Time.deltaTime);
     }
 
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
avatar image
0

Answer by Narosenla · Jun 12, 2017 at 11:48 AM

 public float speed = 0.5f;
 public Transform Player;

 
 // Use this for initialization
 void Start () {
     
 }
 
 // Update is called once per frame
 void Update () {

     Vector3 displacement = Player.position -transform.position;
     displacement = displacement.normalized;

     if (Vector2.Distance (Player.position, transform.position) > 1.0f) {
         transform.position += (displacement * speed * Time.deltaTime);
                      
     }else{
                    //do whatever the enemy has to do with the player
             }

     
 }

 

}

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

24 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

Related Questions

AI Awareness 2 Answers

AI is not moving where it is supposed to? 1 Answer

I cant make a transform get a random position? 1 Answer

AI won't move when Instantiated but will if i drag them in? 0 Answers

Want to apply "height" to my DeadSpace Camera --> Physics.Linecast gives me trouble 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