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 ragefordragons · Aug 20, 2018 at 03:23 PM · movementnot workingfollow playerartificial intelligence

AI is not moving where it is supposed to?

So a while back I was working on some AI code and got it to work how I wanted, and then after using unity collaborate one time it broke my entire project. Now I am rebuilding it, and for some reason my AI is not working like it used to. (Idk if it has anything to do with the collborate issue but its broken now so) What it is supposed to do is move towards the player while your inrange, and when your not, wander randomely within a set area (kind of.) Now it doesnt seem to follow the player at all and just moves in a random direction.

Heres my code if you have any ideas:

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class GruntAI : MonoBehaviour {

 public float moveSpeed;

  
 public float shootSpeed;

 private bool inRange;


 public float patrolArea;
 

 private Transform playerPosition;

 private Vector2 randPosition;

 private Rigidbody2D rb;

 public GameObject shot;
 private Transform thisPos;

 private bool CanShoot;

 private float bullets;
 public float maxBullets;
 public float burstSpeed;


 private bool Restoring;

 // Use this for initialization
 void Start () {


     playerPosition = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();  // this gets the position of the player so the AI can use it 

     inRange = false;

     randPosition = new Vector2(Random.Range(patrolArea * -1, patrolArea), Random.Range(patrolArea * -1, patrolArea)); // this gets a random vector2 so the AI can use it to wander

     rb = GetComponent<Rigidbody2D>();
     InvokeRepeating("generatePosition", 0, 1); // starts the generate position class every second

     thisPos = GetComponent<Transform>();

     CanShoot = true;

     bullets = maxBullets;

     Restoring = false;

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

     if (inRange == true) // this checks if the okayer is in range of the AI and starts moving towards it
     {


        rb.velocity = (playerPosition.position - transform.position).normalized * moveSpeed * Time.deltaTime;

         if (CanShoot == true && bullets > 0)
         {
             CanShoot = false;
             bullets = bullets - 1;
             Instantiate(shot, thisPos.position, Quaternion.identity);
             StartCoroutine(reload());

         }


     } else
     {

         rb.velocity = (new Vector3(randPosition.x, randPosition.y, 0) - transform.position).normalized * moveSpeed / 2 * Time.deltaTime; // otherwise constantly moves towards a new random position
     }

     
     if (bullets < 1 && Restoring == false)
     {
         Restoring = true;
         StartCoroutine(restoreBullets());
     }
     
     
 }


 private void OnTriggerEnter2D(Collider2D other) // checks if player is in range
 {
     if (other.tag == "Player")
     {

     inRange = true;

     }
 }

 private void OnTriggerExit2D(Collider2D other) // checks if player is out of range
 {
     if (other.tag == "Player")
     {
         inRange = false;

     }
 }

 public void generatePosition()
 {
     randPosition = new Vector2(Random.Range(-patrolArea, patrolArea), Random.Range(-patrolArea, patrolArea));
 }

 IEnumerator reload() // the amount of time in between each shot
 {
     yield return new WaitForSeconds(shootSpeed);
     CanShoot = true;
 }

 IEnumerator restoreBullets() // the class that reloads the bullets once they run out
 {

     
     yield return new WaitForSeconds(burstSpeed);
     Restoring = false;

     bullets = maxBullets;
     
 }


}

Comment
Add comment · Show 3
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 MT369MT · Aug 20, 2018 at 04:52 PM 0
Share

Hi, are you sure you added the tag “Player” to your player and your circle collider (I suppose you use it for the inRange collision).

And is the inRange bool changing when you are near the player or is it always set to false?

avatar image ragefordragons MT369MT · Aug 20, 2018 at 06:40 PM 0
Share

Yeah i made sure the collider is detectin the player and i made sure the tag "player" is on the player. like the bot shoots at you, but it doesnt follow

(also just you have been helping me on like all this AI stuff which is funny)

avatar image toddisarockstar · Aug 21, 2018 at 03:03 AM 0
Share

with a problem like this there is is a processes for finding out exactly where the problem is. under each part of code that is suspeced of not working put a print statement;

     print("this part of my code is working"+SomeVariableThatshouldBeWhatever);


then look at the console for what is missing. you can find out where things are going wrong very quickly this way. of course remove the print statement after you find the problem when you are fixed!!!!

1 Reply

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

Answer by Oarcinae · Aug 21, 2018 at 03:41 PM

If you haven't yet, put a bunch of debug prints inside your ontrigger events to see if it's doing what you expect.

Whenever I don't know where something is broken, that's my default. Just fill in a bunch of Debug.Log() statements throughout your code at key sections and test to see what is being hit and what isn't.

Comment
Add comment · Show 4 · 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 ragefordragons · Aug 21, 2018 at 03:45 PM 0
Share

Yeah, I tried that many times. I made sure that the Player was being detected, made sure that the random location actually was getting values, made sure that the player location had values, made sure the if else statem,ents were working (i mean the enemy still shoots at the player so for sure its detecting and geting his position) so I think it has to do with something related to 2d physics....

avatar image Oarcinae ragefordragons · Aug 21, 2018 at 03:47 PM 0
Share

If you've checked all of that, which specific part of the code is failing? inRange is being set to true? Just not the velocity of the AI?

avatar image ragefordragons Oarcinae · Aug 21, 2018 at 11:52 PM 1
Share

Okay I got it, so the problem was that the enemy still had gravity enabled on its rigidbody which is something I thought I checked origionaly but hey It works now. Thanks though!

Show more comments

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

144 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

Related Questions

Moving an object using rigidbody.AddForce & keyboard input. 1 Answer

ENEMY MOVEMENT SCRIPT 0 Answers

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

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

there is a chance that my caracter doesnt move 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