Search Unity

limiing distance between objects

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

  1. xxfelixlangerxx

    xxfelixlangerxx

    Joined:
    Feb 6, 2019
    Posts:
    31
    Hey how do i limit the distance between two objects in my 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.         transform.LookAt(playerpos.position);
    17.  
    18.         distance = Vector3.Distance(transform.position, playerpos.position);
    19.         if (distance > maxdistance)
    20.         {
    21.             rbenemy.AddForce(transform.forward * enemymovespeed, ForceMode.Force);
    22.         }
    23.         else
    24.         {
    25.             distance = maxdistance; //of course this dosnt do anything just a filler line
    26.  
    27.         }
    28.     }
    29.  
    30.     private void OnCollisionEnter(Collision collision)
    31.     {
    32.         if (collision.gameObject.tag == ("Player"))
    33.         {
    34.             PlayerMovementS.Health -= 1f;
    35.         }
    36.     }
    37.     private void OnDestroy()
    38.     {
    39.         DataManagerS.Enemyskilled += 1;
    40.     }
     
  2. qkson

    qkson

    Joined:
    Jan 15, 2018
    Posts:
    77
    Code (CSharp):
    1.         else
    2.         {
    3.             distance = maxdistance; //of course this dosnt do anything just a filler line
    4.             //IN HERE
    5.         }
    if distance<maxdistance then you can move the object back to maxdistance via Lerp or any other option, or you can just stop moving when distance is close to maxdistance. Everything depends on how you want it to look like
     
  3. TimmyTheTerrible

    TimmyTheTerrible

    Joined:
    Feb 18, 2017
    Posts:
    186
    Vector subtraction to the rescue!

    So if you subtract vector B from vector A like this: A - B = C, then what you get is another vector (C) that points from B in the direction of A.

    Since you want to limit the distance an object can get you would do something like :

    Code (CSharp):
    1. // limit the distance a can get from b.
    2. // get the direction from b to a.
    3. Vector3 c = a - b;
    4. // make it unit length so we can multiply it by max distance
    5. c.Normalize();
    6. c *= maxDistance;
    7.  
    8. // adding the scaled direction vector back to B gives us the vector we are looking for.
    9. a = c + b;
     
    CenkayB3 likes this.