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 SS1 · Sep 23, 2015 at 11:15 AM · networkingplayerenemyfollowing

Make an enemy follow a player through network

Hi I'm making a networking game, I can't get my enemy's to follow other player than the first player that is spawn in when the server starts. Here is my code :

 using UnityEngine;
 using System.Collections;
 using UnityEngine.Networking;
 
 public class MoveToPlayer : NetworkBehaviour 
 {
     public Transform target; //the enemy's target
     public GameObject[] go;
     public float moveSpeed = 3f; //move speed
     public float rotationSpeed = 3f; //speed of turning
     public float range = 20f;
     public float range2 = 20f;
     private float stop = 5;
     public Transform myTransform; //current transform data of this enemy
 
     void Awake()
     {
         myTransform = transform; //cache transform data for easy access/preformance
     }
   
     void Start()
     {
         
         
     }
   
     void Update () 
     {
         if (!isLocalPlayer) 
         {
             CmdMoving ();
         }
         else if (isLocalPlayer)
         {
             CmdMoving ();
         }
         else 
         {
             CmdMoving ();
         }
     }
 
     void CmdMoving ()
     {
         GameObject go = GameObject.FindGameObjectWithTag("Player");
         target = go.transform;        
         //rotate to look at the player
         var distance = Vector3.Distance (myTransform.position, target.position);
         if (distance <= range2 && distance >= range) 
         {
             myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
             Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
         } 
         else if (distance <= range && distance > stop) 
         { 
             //move towards the player
             myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
             Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
             myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
         } 
         else if (distance <= stop) 
         {
             myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
             Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
         }
     }
 }

Thanks in advance.

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 SS1 · Sep 29, 2015 at 09:11 AM 0
Share

This was my solution, i also made it shot

 using UnityEngine;
 using System.Collections;
 using UnityEngine.Networking;
 
 public class $$anonymous$$oveToPlayer : NetworkBehaviour 
 {
     public Transform target; //the enemy's target
     public float moveSpeed = 3f; //move speed
     public float rotationSpeed = 3f; //speed of turning
     public float range = 20f;
     public float range2 = 20f;
     private float stop = 10;
     public Transform myTransform; //current transform data of this enemy
     private Layer$$anonymous$$ask raycastLayer;
 
     //Shooting
     public GameObject shot;
     public Transform shotSpawn;
     private int randomCount;
 
     void Awake()
     {
         myTransform = transform; //cache transform data for easy access/preformance
     }
   
     void Start()
     {
         raycastLayer = 1 << Layer$$anonymous$$ask.NameToLayer ("Player"); //target the player
     }
   
     void FixedUpdate () 
     {
         moveToTarget ();
     }
 
     void Update ()
     {
         randomCount = Random.Range (1, 100);
         if (!isServer) 
             return;
 
         var distance2 = Vector3.Distance(myTransform.position, target.position);
         if (distance2 <= range) 
         {
             CmdDoFire ();            
         }    
     }
 
     void moveToTarget ()
     {
         if (!isServer)
             return;
 
         if (target != null && isServer) 
         {
             Collider[] distance = Physics.OverlapSphere (myTransform.position, range, raycastLayer);
             
             if (distance.Length > 0) 
             {
                 int rando$$anonymous$$t = Random.Range (0, distance.Length);
                 target = distance[rando$$anonymous$$t].transform;
             }
             
             var distance1 = Vector3.Distance(myTransform.position, target.position);
             
             if (distance1 <= range2 && distance1 >= range) 
             {
                 myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
                  Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
             } 
             else if (distance1 <= range && distance1 > stop) 
             { 
                 //move towards the player
                 myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
                 Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
                 myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
             } 
             else if (distance1 <= stop) 
             {
                 myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
                  Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
             }
         }
     }
 
     [Command]
     void CmdDoFire ()
     {
         if (randomCount < 2) 
         {
             GameObject instance = (GameObject)Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
             GetComponent<AudioSource> ().Play ();
             NetworkServer.Spawn (instance);
         }
     }
 }
 

4 Replies

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

Answer by SS1 · Sep 29, 2015 at 09:15 AM

This is my solution was this, I also made it shot

using UnityEngine; using System.Collections; using UnityEngine.Networking;

 public class MoveToPlayer : NetworkBehaviour 
 {
     public Transform target; //the enemy's target
     public float moveSpeed = 3f; //move speed
     public float rotationSpeed = 3f; //speed of turning
     public float range = 20f;
     public float range2 = 20f;
     private float stop = 10;
     public Transform myTransform; //current transform data of this enemy
     private LayerMask raycastLayer;
 
     //Shooting
     public GameObject shot;
     public Transform shotSpawn;
     private int randomCount;
 
     void Awake()
     {
         myTransform = transform; //cache transform data for easy access/preformance
     }
   
     void Start()
     {
         raycastLayer = 1 << LayerMask.NameToLayer ("Player"); //target the player
     }
   
     void FixedUpdate () 
     {
         moveToTarget ();
     }
 
     void Update ()
     {
         randomCount = Random.Range (1, 100);
         if (!isServer) 
             return;
 
         var distance2 = Vector3.Distance(myTransform.position, target.position);
         if (distance2 <= range) 
         {
             CmdDoFire ();            
         }    
     }
 
     void moveToTarget ()
     {
         if (!isServer)
             return;
 
         if (target != null && isServer) 
         {
             Collider[] distance = Physics.OverlapSphere (myTransform.position, range, raycastLayer);
             
             if (distance.Length > 0) 
             {
                 int randomint = Random.Range (0, distance.Length);
                 target = distance[randomint].transform;
             }
             
             var distance1 = Vector3.Distance(myTransform.position, target.position);
             
             if (distance1 <= range2 && distance1 >= range) 
             {
                 myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
                  Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
             } 
             else if (distance1 <= range && distance1 > stop) 
             { 
                 //move towards the player
                 myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
                 Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
                 myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
             } 
             else if (distance1 <= stop) 
             {
                 myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
                  Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
             }
         }
     }
 
     [Command]
     void CmdDoFire ()
     {
         if (randomCount < 2) 
         {
             GameObject instance = (GameObject)Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
             GetComponent<AudioSource> ().Play ();
             NetworkServer.Spawn (instance);
         }
     }
 }
 
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 CoffeeOD · Sep 25, 2015 at 07:57 AM

Hi, this video might give you some ideas: https://www.youtube.com/watch?v=7Kk1D4v3vIg∈dex=14&list=PLwyZdDTyvucyAeJ_rbu_fbiUtGOVY55BG, there is short tutorial how to make enemy follow an target.

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 SS1 · Sep 29, 2015 at 09:11 AM

Ok this was my solution for those may need it, it also can shot at a target

using UnityEngine; using System.Collections; using UnityEngine.Networking;

public class MoveToPlayer : NetworkBehaviour { public Transform target; //the enemy's target public float moveSpeed = 3f; //move speed public float rotationSpeed = 3f; //speed of turning public float range = 20f; public float range2 = 20f; private float stop = 10; public Transform myTransform; //current transform data of this enemy private LayerMask raycastLayer;

 //Shooting
 public GameObject shot;
 public Transform shotSpawn;
 private int randomCount;

 void Awake()
 {
     myTransform = transform; //cache transform data for easy access/preformance
 }
  
 void Start()
 {
     raycastLayer = 1 << LayerMask.NameToLayer ("Player"); //target the player
 }
  
 void FixedUpdate () 
 {
     moveToTarget ();
 }

 void Update ()
 {
     randomCount = Random.Range (1, 100);
     if (!isServer) 
         return;

     var distance2 = Vector3.Distance(myTransform.position, target.position);
     if (distance2 <= range) 
     {
         CmdDoFire ();            
     }    
 }

 void moveToTarget ()
 {
     if (!isServer)
         return;

     if (target != null && isServer) 
     {
         Collider[] distance = Physics.OverlapSphere (myTransform.position, range, raycastLayer);
         
         if (distance.Length > 0) 
         {
             int randomint = Random.Range (0, distance.Length);
             target = distance[randomint].transform;
         }
         
         var distance1 = Vector3.Distance(myTransform.position, target.position);
         
         if (distance1 <= range2 && distance1 >= range) 
         {
             myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
              Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
         } 
         else if (distance1 <= range && distance1 > stop) 
         { 
             //move towards the player
             myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
             Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
             myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
         } 
         else if (distance1 <= stop) 
         {
             myTransform.rotation = Quaternion.Slerp (myTransform.rotation,
              Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
         }
     }
 }

 [Command]
 void CmdDoFire ()
 {
     if (randomCount < 2) 
     {
         GameObject instance = (GameObject)Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
         GetComponent<AudioSource> ().Play ();
         NetworkServer.Spawn (instance);
     }
 }

}enter code here

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 Graham-Dunnett ♦♦ · Sep 29, 2015 at 09:11 AM 0
Share

Please format your script code....

avatar image
0

Answer by Eno-Khaon · Sep 29, 2015 at 06:35 AM

The first thought that comes to mind is in regard to your usage of "FindGameObjectWithTag()"

That function limits you to a single result, which will most likely be the first player spawned with the lowest ObjectID associated with it.

What you should consider is using "FindGameObjectsWithTag()" (note that it's plural) to get an array of GameObjects instead. Then, you can iterate through them and select a random target, the nearest one, the nearest the enemy has line of sight to, etc.

That said, FindGameObject(s)WithTag() (either singular or plural) is a very expensive operation. I would suggest storing the list of possible player targets whenever a player joins or leaves the game (or dies and respawns, or whatever) and update it only when necessary.

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Problem| Player Name Above The Player 2 Answers

C # script the enemy chases the player. 2 Answers

Enemy can't find weapon collider 0 Answers

NavMesh problem it does not respond corectly 0 Answers

Network disconnect player 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