- Home /
Get an object to trail behind you
using UnityEngine;
using System.Collections;
public class KeepDistance : MonoBehaviour {
// Use this for initialization
void Start () {
}
//Restricts the position of this object to be within a distance of "distance" of "center"
public float distance = -40;
public Transform center;
// Update is called once per frame
void Update () {
float dst = Vector3.Distance(center.position, transform.position);
if (dst > distance)
{
Vector3 vect = center.position - transform.position;
vect = vect.normalized;
vect *= (dst-distance);
transform.position += vect;
}
}
}
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.
Answer by darker9999 · Nov 28, 2012 at 06:36 AM
I can't quite remember but I believe that Vector3.Distance is always positive, to confirm this use print("dst"). If this is the case make distance = 40. Also remember that Vector3.Distance acts like a radius, this means that while the object my be 40 away from the player this doesn't have to be behind them.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
A node in a childnode? 1 Answer
Is it possible to give certain number to Time.deltaTime? 1 Answer