Search Unity

Limiting distance between two objects and enemy movement

Discussion in 'Scripting' started by xxfelixlangerxx, Mar 17, 2019.

  1. xxfelixlangerxx

    xxfelixlangerxx

    Joined:
    Feb 6, 2019
    Posts:
    31
    Hey I need help with enemy movement and limiting the distance between the enemy and player.
    For more information read the comments in the script.
    Code (CSharp):
    1. public Transform playerpos;
    2.     public Rigidbody rbenemy;
    3.     public float enemymovespeed;
    4.     public float maxdistance;
    5.     public float distance;
    6.    
    7.  
    8.     void Start()
    9.     {
    10.         DataManagerS.currentenemylvl += 1;
    11.         playerpos = GameObject.Find("Player").GetComponent<Transform>();
    12.     }
    13.  
    14.     private void Update()
    15.     {
    16.         distance = Vector3.Distance(transform.position, playerpos.position);
    17.         if (distance > maxdistance) //now move towards the player
    18.         {
    19.             rbenemy.AddForce(transform.forward * enemymovespeed, ForceMode.Impulse);
    20.             //is there a better way to do this, cus like this the enemy just flies away the player and takes ages to come back
    21.         }
    22.         else
    23.         {
    24.             distance = maxdistance;
    25.             //now limit the distance
    26.         }
    27.         //used to move to the player
    28.         transform.LookAt(playerpos.position);
    29.     }
    30.  
    31.     private void OnCollisionEnter(Collision collision)
    32.     {
    33.         if (collision.gameObject.tag == ("Player"))
    34.         {   //killing the player
    35.             PlayerMovementS.Health -= 1f;
    36.         }
    37.     }
    38.     private void OnDestroy()
    39.     {
    40.         DataManagerS.Enemyskilled += 1;
    41.     }
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    You should only be applying physics forces inside FixedUpdate, not Update. That may explain why you're getting inconsistent speeds.

    What other actual issues are you having?