• 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 redwiz666 · Sep 08, 2019 at 09:15 PM · 2dai

Issues with 2d wandering

I writing a game that has the enemy's wander around the map if they don't detect the Player within a specific range. When the enemies are walking around if they hit a object I use "transform.forward = wayPoint - transform.position;" to change their direction which seems to make them walk in a different direction but it seems to only make them go back the way they game. I'm trying to make them pick a new random location on the map but it doesn't seem to be working out right. Also when I change the transform.forward the sprints turn side ways (which isn't what I was trying to do) but I can't seem to find another method that will allow them to change direction. Below is my code and a gif showing the issue I'm having. Any help would be greatly appreciated.

alt text

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 public enum States{
     idle,
     wander,
     attack
 }
 public class EnemyAI : MonoBehaviour
 {
     //For Aggro
     [Header("Aggro")]
     [SerializeField]
     public float lookRadius = 10f;   // How far our NPC can see
     public float npcFOV = 90f;    // How wide our NPC can see
     public GameObject player;  
     public bool PlayerSeen;     // If the Enemy has seen the Player
    
     //For Wondering
     [Header("Wondering Settings")]
     [SerializeField]
     internal Vector3 wayPoint;
     public float wanderRadius = 40f;    // How far we can wonder
     public float wanderTimer = 5f;      // How long in between Decisions
     public float wanderSpeed = 2f;
     public bool wandering;
    
     //For Chasing player
     [Header("Chasing Settings")]
     [SerializeField]
     public float chaseSpeed = 2f;
     public float minDis = 2f;
     // Start is called before the first frame update
     void Start()
     {
         player = GameObject.FindGameObjectWithTag("Player") as GameObject;
         wander();
     }
 
     // Update is called once per frame
     void Update()
     {
         ai_Brain();
        
     }
    
    void OnCollisionEnter2D(Collision2D collision)
     {
         if (collision.gameObject.tag == "blocking")
         {
             //collision.gameObject.SendMessage("ApplyDamage", 10);
             Debug.Log("We hit: " +collision.gameObject.name);
             wander();
         }
     }
 
     void ai_Brain(){
        
         // Collider[] objectsFound = Physics.OverlapSphere(transform.position, lookRadius);
         // foreach(Collider thing in objectsFound){
         //     if (thing.tag == "Player") {
         //         // Player is within our lookRadius
         //         Vector3 targetDir = player.transform.position - transform.position;
         //         Vector3 forward = transform.forward;
         //         float angle = Vector3.Angle(targetDir, forward);
         //         Debug.Log ("Player at Angle: "+angle.ToString());
         //         if (angle < npcFOV){
         //             Vector3 direction = ( player.transform.position - transform.position ).normalized;
         //             RaycastHit hit;
         //             if ((Physics.Raycast (transform.position, direction, out hit, lookRadius) && hit.collider.tag == "Player")) {
         //                 // hit.collider.gameObject.GetComponent<Unit> ().isSeen = true;
         //                 PlayerSeen = true;
         //                 Debug.Log ("We can see the Player!");
         //             }
         //         }
         //         else{
         //             // Since player wasn't within our FOV
         //             break;
         //         }
         //     }
         // }
        
         // Get Distance to the player
         float dist = Vector3.Distance (player.transform.position, transform.position);
         // Check if Player if farther then we can see
         if (dist <= lookRadius){
             Debug.Log ("Player Distance: "+dist.ToString());
             Vector3 targetDir = player.transform.position - transform.position;
             Vector3 forward = transform.forward;
             float angle = Vector3.Angle(targetDir, forward);
             Debug.Log ("Player at Angle: "+angle.ToString());
             // Check if player is within our FOV
             if (angle < npcFOV){
                 Vector3 direction = ( player.transform.position - transform.position ).normalized;
                 // need to rewrite for Physics2D
                 RaycastHit hit;
                 if ((Physics.Raycast (transform.position, direction, out hit, lookRadius) && hit.collider.tag == "Player")) {
                     // hit.collider.gameObject.GetComponent<Unit> ().isSeen = true;
                     PlayerSeen = true;
                 }
                 // Chase Player
                 transform.position = Vector2.MoveTowards(transform.position, player.transform.position, chaseSpeed * Time.deltaTime);
                 // agent.ResetPath();
                 // agent.SetDestination(player.transform.position);
                 if (dist <= minDis){
                     // Since we are next to Player
                     // ATTACK!!!
                 }
             }
            
         }
         else {
             // Since we can't see any Player we Wonder around
            
             Wandering();
         }
     }
    
     void Wandering(){
         //Used for Wandering around
         transform.position += transform.TransformDirection(Vector3.forward) * wanderSpeed * Time.deltaTime;
         if ((transform.position - wayPoint).magnitude < 3)
         {
             // when the distance between us and the target is less than 3
             // create a new way point target
             Debug.Log("Wandering Around");
             wander();
         }
         RaycastHit2D hit;
         GetComponent<BoxCollider2D> ().enabled = false;
         hit = Physics2D.Raycast(transform.position, Vector2.zero);
         Debug.DrawRay (transform.position, transform.forward, Color.cyan);
         GetComponent<BoxCollider2D> ().enabled = true;
         // Check if we are hitting a object
         if (hit.collider != null) {
             Debug.Log ("I'm hitting "+hit.collider.name);
             // We hit something so pick a new direction
             wander();
         }
     }
     void wander()
     {
          // does nothing except pick a new destination to go to
          wayPoint = new Vector3(Random.Range(transform.position.x - wanderRadius, transform.position.x + wanderRadius), 1, Random.Range(transform.position.z - wanderRadius, transform.position.z + wanderRadius));
          wayPoint.y = 1;
          // don't need to change direction every frame seeing as you walk in a straight line only
          transform.forward = wayPoint - transform.position;
     }
 }
wandering-issue.gif (187.8 kB)
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 ejoo_pasco · Sep 09, 2019 at 09:39 PM 0
Share

Hi redwiz666, Looks like they're rolling out of game-orientation ins$$anonymous$$d of turning around. - Is the game x-z-orientated? - Is transform.position.y at 1.0f (like you set waypoint to) when the enemies are instantiated?

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.

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

344 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image 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 fix the rotation bug? 1 Answer

Vector 2 only using x (Enemy AI) 1 Answer

AI stops following player. 1 Answer

Trying to impliment a 2D sidescroller enemeny follow player AI. Getting UnassignedReferenceException. Now idea how to fix, been lurking for days 2 Answers

How to get AI to throw object over obstacles 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