Search Unity

Getting Object distance behind player

Discussion in 'Scripting' started by dbz987, Nov 27, 2012.

  1. dbz987

    dbz987

    Joined:
    Oct 1, 2012
    Posts:
    15
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class KeepDistance : MonoBehaviour {
    5.  
    6.     // Use this for initialization
    7.     void Start () {
    8.    
    9.     }
    10.     //Restricts the position of this object to be within a distance of "distance" of "center"
    11.     public float distance = 40;
    12.     public Transform center;
    13.     // Update is called once per frame
    14.     void Update () {
    15.        
    16.         float dst = Vector3.Distance(center.position, transform.position);
    17.         if (dst > distance)
    18.         {
    19.             Vector3 vect = center.position  - transform.position;
    20.             vect = vect.normalized;
    21.             vect *= (dst-distance);
    22.             transform.position += vect;
    23.    
    24.     }
    25. }
    26. }  
    I need to keep the object trailing behind the player. When I have a positive number for the variable distance the object stays in front of me at the same distance. When I have a negative number for the variable distance the object blinks in front and in back of the player.
     
    Last edited: Nov 28, 2012
  2. dbz987

    dbz987

    Joined:
    Oct 1, 2012
    Posts:
    15
    anyone?
     
  3. BPPHarv

    BPPHarv

    Joined:
    Jun 9, 2012
    Posts:
    318
    There's really no such thing as a negative distance, there's a distance in another direction but this is still a positive distance.

    What it seems you want to do though is compare the trailing object's current position with the desired rear position. The desired rear position would be a point projected along the negative z axis of the target by some distance. Your follower object would then move as close as possible to THAT position.

    Assuming center is the name of the Transform that the object is trying to stay near to, and distance is the minimum distance this object will follow at; the desired rear position would be:
    Code (csharp):
    1.  
    2. Vector3  rearPoint  = center .position - (center .forward*distance);
    3.