Search Unity

Limiting distance between two objects and enemy movement

Discussion in 'Scripting' started by xxfelixlangerxx, Mar 18, 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.     void Start()
    8.     {
    9.         DataManagerS.currentenemylvl += 1;
    10.         playerpos = GameObject.Find("Player").GetComponent<Transform>();
    11.     }
    12.     private void Update()
    13.     {
    14.         distance = Vector3.Distance(transform.position, playerpos.position);
    15.         if (distance > maxdistance) //now move towards the player
    16.         {
    17.             rbenemy.AddForce(transform.forward * enemymovespeed, ForceMode.Impulse);
    18.             //is there a better way to do this, cus like this the enemy just flies away the player and takes ages to come back
    19.         }
    20.         else
    21.         {
    22.             distance = maxdistance;
    23.             //now limit the distance
    24.         }
    25.         //used to move to the player
    26.         transform.LookAt(playerpos.position);
    27.     }
    28.     private void OnCollisionEnter(Collision collision)
    29.     {
    30.         if (collision.gameObject.tag == ("Player"))
    31.         {   //killing the player
    32.             PlayerMovementS.Health -= 1f;
    33.         }
    34.     }
    35.     private void OnDestroy()
    36.     {
    37.         DataManagerS.Enemyskilled += 1;
    38.     }
     
  2. zioth

    zioth

    Joined:
    Jan 9, 2019
    Posts:
    111
    Your AddForce is moving the enemy in its own forward direction, which has nothing to do with the player's position. I think you want something like "playerpos.position - transform.position" as your force direction, but that's just off the top of my head, so you may have to fiddle with it.

    Your line "distance = maxdistance" doesn't do anything, since you don't use the distance variable anywhere outside this function.