# How to calculate distance between objects?

Im a little noob in the unity enviroment, but, i need that one rigidbody2d find the nearest object with a specific tag, and then, move to them. I tried tons of things, tons of diferents arrays, findobjectswithtag();, but i dont know how to manipulate the transform data to achieve this. I think that is pretty basic, but i cant handle…

Do you can write an example please?

Thanks.

• Use SphereCast to get gameobjects in certain radius, then loop through them and get whatever you want.
• Use Vector3.Distance to get the distance.

okay, simple example of finding the closest object with a tag

``````GameObject FindClosestTag(string tag){

//get all the gameobjects with a tag
GameObject[] tagged = GameObject.FindGameObjectsWithTag(tag);
//closest object found so far
GameObject closest = null;
//the shortest distance we've found so far
float shortestDistance = float.PositiveInfinity;
//loop trough all gameobjects we found with the tag
foreach(GameObject go in tagged){
//we don't want to have ourself be an option for the closest object
if(go != this.gameObject){
//the distance to the current gameobject
float currentDistance = Vector3.Distance(transform.position, go.transform.position);
//this object is closer than the closest one so far
//this one becomes the closest one so far
if(currentDistance < shortestDistance){
shortestDistance = currentDistance;
closest = go;
}
}
}

//return the gameobject we found
return closest;
}
``````

not a very optimized code snip, but should do what you need.

Here is some code to get you started on how to move towards another object within a certain distance:

``````using UnityEngine;
using System.Collections;

public class ObjectA : MonoBehaviour {

// The distance beneath which objectA will move towards objectB in world units

// Speed of this object when moving towards the target
public float speed = 1f;

// The target to follow
private GameObject objectB;

// Our own rigidbody
private Rigidbody2D rb;

void Start () {

// Get the rb2D component from this object
rb = GetComponent<Rigidbody2D>();

// Find the other object by Tag, it must already exist on scene creation
objectB = GameObject.FindGameObjectWithTag("tagofObjectB");
}

// FixedUpdate because we are moving rigidbody that need to be in sync with other Physics actions
void FixedUpdate () {

// Calculate the distance between both objects
float distance = Vector3.Distance(objectB.transform.position, transform.position);

// If the distance is smaller than the given threshold

// Calculate the direction from our object to objectB
Vector2 direction = objectB.transform.position - transform.position;

// Move with our rigidbody towards the other object in a straight line
// Can be stopped by other colliders or forces
rb.MovePosition(rb.position + direction * speed * Time.fixedDeltaTime);
}
}
}
``````

Try this out dude. It’s what I’m currently doing now to determine the distance of my AI Character and Player. So like if it’s too close then he’ll do this thingy and if far away he’ll do something else.

``````	public Vector2 RelativePoint;
public Transform YourTransform;

if(YourTarget != null){
RelativePoint = YourTransform.InverseTransformPoint(YourTarget.transform.position);

}
``````

Attach this code to your Character or what ever object you’d like to use then

Drag Your GameObject with the script into the YourTransform

And then next

Create a GameObject (or not) Drag that GameObject into your public Gameobject named YourTarget

Start the game and you’ll see numbers ranging in your Public Vector RelativePoint.

Pretty simple man. It works for me, I hope it does the same for you as well.

: )

Ok, i saw my error, i actually do everything right, only i use incorrectly the “go” in: foreach (GameObject go in tagged)