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
0
Question by cem · Dec 23, 2010 at 07:33 PM · pathfindingmodification

Modification of AIFollow.cs Pathfinding

I modified the code AIFollow.cs and i add the functions code. And this functions are GetEnemies() and FindClosest() . I want to try Real Time Strategy game and i also use it for A* pathfinding. There are not working. GetEnemies() create an array which includes "Target" tag of GameObjects. But it is not working.

Any help i will appriciate.

Here is the Code:

using UnityEngine;

using System.Collections;

public class AIFollow : MonoBehaviour { //[RequireComponent (typeof(CharacterController))] public float speed = 3.0F; public float rotationSpeed = 5.0F; public float pickNextWaypointDistance = 3.0F; public float SearchWaypointFrequency = 0.2F; public float maxStop = 3;

public bool continousTargetSearch = false; public float targetSearchFrequency = 1.0F; private bool canSearchAgain = true; public Command command = Command.Stay;

public Transform target; private CharacterController controller; private AIAnimation animator; private Seeker seeker;

public Vector3 myPosition; public Transform[] enemies; public float distance;

// Make sure there is always a character controller

public enum Command { Stay, Walk }

public IEnumerator Start () { //public IEnumerator Start ()

 waypointPosition = transform.position;
 command = Command.Stay;
 controller = GetComponent (typeof(CharacterController)) as CharacterController;
 Object anim = GetComponent (typeof(AIAnimation));
 animator = anim != null ? anim as AIAnimation : null;
 seeker = GetComponent (typeof(Seeker)) as Seeker;

 StartCoroutine (Patrol());
 yield return new WaitForSeconds (Random.value*0.5F);

 if (continousTargetSearch) {
     StartCoroutine (SearchPlayer());
 }

 //here is the start array operations
 GetEnemies();    
 myPosition = transform.position;    
 target = FindClosest(enemies);
 distance=Vector3.Distance(target.position,transform.position);

 while (true) {
     FindPoint (curpoint);
     yield return new WaitForSeconds (SearchWaypointFrequency);
 }

}

private Vector3 waypointPosition; //private bool continuous = false; private Vector3[] points; private int curpoint = 0;

public void Update () { //Debug.color = Color.blue; Debug.DrawLine (transform.position, waypointPosition, Color.blue);

 //Stop();
 Start();
 /*GetEnemies();    
 myPosition = transform.position;    
 target = FindClosest(enemies);
 distance=Vector3.Distance(target.position,transform.position);*/

}

public IEnumerator SearchPlayer () { yield return 0; while (true) { yield return 0; while (!canSearchAgain) { yield return 0; } if (continousTargetSearch) { canSearchAgain = false; seeker.StartPath (transform.position,target.position); } yield return new WaitForSeconds (targetSearchFrequency); }

}

public void PathComplete (Vector3[] newPoints) { canSearchAgain = true; points = newPoints; FindPoint (0); command = Command.Walk; }

public void PathError () { canSearchAgain = true; }

public bool HasReachedTarget () { return curpoint >= points.Length; }

public void FindPoint (int cpoint) { curpoint = cpoint; if (points == null || points.Length == 0 || curpoint >= points.Length) {
waypointPosition = transform.position; Stop (); return; }

 if (points.Length == 1) {
     waypointPosition = points[0];
     command = Command.Walk;
     return;
 }

 command = Command.Walk;

 waypointPosition = points[curpoint];
 Vector3 p = waypointPosition;
 p.y = transform.position.y;

 if (curpoint < points.Length - 1) {
     if ((transform.position-p).sqrMagnitude < pickNextWaypointDistance*pickNextWaypointDistance) {
         curpoint++;
         FindPoint (curpoint);
     }

 } else {
     if ((transform.position-p).sqrMagnitude < maxStop*maxStop) {
         curpoint++;
         FindPoint (curpoint);
     }
 }

}

public IEnumerator Patrol () { while (true) { if (command == Command.Walk) { MoveTowards(waypointPosition); }

     yield return 0;
 }

}

public void Stop () { command = Command.Stay; if (animator != null) { animator.SetSpeed (0.0F); } }

public void RotateTowards (Vector3 position) { if (animator != null) { animator.SetSpeed (0.0F); }

 Vector3 direction = position - transform.position;
 direction.y = 0;

 if (curpoint == points.Length - 1 && direction.sqrMagnitude < maxStop*maxStop) {
     FindPoint (curpoint);
     return;
 }

 if (direction.sqrMagnitude < 0.1F*0.1F) {
     return;
 }

 // Rotate towards the target
 transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
 transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);

}

public void MoveTowards (Vector3 position) { Vector3 direction = position - transform.position; direction.y = 0;

 if (direction.sqrMagnitude < 0.2F*0.2F) {
     Stop ();
     return;
 }

 // Rotate towards the target
 transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
 transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);

 // Modify speed so we slow down when we are not facing the target
 Vector3 forward = transform.TransformDirection(Vector3.forward);
 float speedModifier = Vector3.Dot(forward, direction.normalized);
 speedModifier = Mathf.Clamp01(speedModifier);

 // Move the character
 if (controller) {
     direction = forward * speed * speedModifier*speedModifier;
     controller.SimpleMove(direction);
 } else {
     direction = forward * speed * speedModifier*speedModifier;
     transform.Translate (direction*Time.deltaTime,Space.World);
 }

 if (animator != null) {
     animator.SetSpeed (speed * speedModifier);
 }

}

public void GetEnemies(){ // Get enemies from the Scene

 GameObject[] enemyObjects = GameObject.FindGameObjectsWithTag("Target");

 Transform[]  enemies = new Transform[enemyObjects.Length];   

 for (int i = 0; i < enemyObjects.Length; i++) 
 {           
         enemies[i] = enemyObjects[i].transform;
     Debug.Log("GetEnemies() : count = " + i );
 }

 Debug.Log("GetEnemies() : enemy count = " + enemies.Length);

}

public Transform FindClosest(Transform[] targets) // Find Closest enemy { Debug.Log("FindClosest() : ---------------> " +targets.Length);

     GameObject[] enemyObjects = GameObject.FindGameObjectsWithTag("Target");

     float closestDistance = (enemies[0].position-myPosition).sqrMagnitude;  

     int targetNumber=0;

     for(int i=1; i<targets.Length ;i++)
     {

         float thisDisatance = (enemies[i].position-myPosition).sqrMagnitude;

             if(thisDisatance<closestDistance)
             {

                 closestDistance=thisDisatance;
                 targetNumber=i;

             }   
     }       

     return enemies[targetNumber];

 }       

}

enemy must detect the target from an array and goes through it. Then Fire() and Destroy "target". After getting another target from an array and goes to the next target.

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

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.

Follow this Question

Answers Answers and Comments

No one has followed this question yet.

Related Questions

walking through the countryside ? 1 Answer

2D alternative to Physics.CheckSphere 2 Answers

Patfinding cant change destination Target 0 Answers

Connecting the dots 0 Answers

Navmesh with destructible 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