- Home /
How to check if distance between two objects is getting smaller?
Hello,
i want to know how do i check if distance between two objects is getting smaller (in c# if possible).
private GameObject enemy;
enemy=GameObject.FindWithTag("Enemy");
float distance=(transform.position-enemy.transform.position).magnitude;
if (distance is getting smaller){ //............ some stuff here
}
Answer by aldonaletto · Nov 23, 2011 at 10:56 AM
You must compare the current distance with the previous one: if it's smaller, the distance has shortened. Anyway, save the current distance to compare in the next Update:
private GameObject enemy;
void Start(){ enemy=GameObject.FindWithTag("Enemy"); }
private float lastDist = 0;
void Update(){ float distance=(transform.position-enemy.transform.position).magnitude; if (distance < lastDist){ // if distance reduced... //............ do some stuff here } lastDist = distance; // don't forget to update last distance! }
Your answer
![](https://koobas.hobune.stream/wayback/20220613052551im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Move an object to a specific distance 0 Answers
How to measure the distance between an Augmented Reality marker and camera? 0 Answers
Tree Billboard Start dont work 2 Answers
Checking for closest gameobject with tag. 5 Answers
Culling low grass details on terrain (detail distance issue for not tall details) 0 Answers