Как найти расстояние между объектами unity

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Your name

Your email

Suggestion*

Cancel

Description

Returns the distance between a and b.

Vector3.Distance(a,b) is the same as (a-b).magnitude.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour { public Transform other;

void Example() { if (other) { float dist = Vector3.Distance(other.position, transform.position); print("Distance to other: " + dist); } } }

Introduction

In this arti­cle we will see dif­fer­ent ways to cal­cu­late the dis­tance between two objects in Uni­ty, this can be use­ful for exam­ple to know how far is the char­ac­ter from a cer­tain point of the sce­nario or to acti­vate mech­a­nisms when the char­ac­ter is at a cer­tain distance.

Dear read­er

In the chan­nel there lots of videos about Blender, Uni­ty and pro­gram­ming
in which we solve dif­fer­ent prob­lems and we pro­vide use­ful infor­ma­tion on these topics.

🍷🧐

Setting up the scene

Let’s make a very sim­ple scene that will have two spheres with 3D texts to indi­cate the num­ber of the sphere and the dis­tance between them.

hierarchy of a project in unity 3d
Fig. 1: These are the GameOb­jects in the scene hierarchy.
assigned script that is in charge of calculating the distance in unity
Fig. 2: Script that will take care of the calculations.

The cam­era will have assigned the Script named “Dis­tances” which is the one that will cal­cu­late the dis­tance and write the val­ues on the screen. As an extra, we’ll add a Line Ren­der­er com­po­nent to draw a line from one object to another. 

In fig­ure 2, we see that there are fields for both objects and for the dis­tance indi­ca­tor. We also have an enum that allows us to choose if we want to cal­cu­late the dis­tance in space or pro­ject­ed in a cer­tain plain.

distance between two gameobjects in unity
Fig. 3: This is how the scene looks with the objects.

Preparing the Script 

The Script that solves the cal­cu­la­tions calls “Dis­tances” (com­plete Script at the end of the arti­cle), in the fol­low­ing fig­ure, we can see the fields defined in this Script and the Start method.

fields and start method to calculate the distance between two positions in unity.
Fig. 4: Fields and Script Start method for cal­cu­lat­ing the dis­tance between two GameObjects.

We have seri­al­ized fields (appear in the inspec­tor) to assign the two spheres from the hier­ar­chy, a TextMesh com­po­nent for the dis­tance indi­ca­tor and the enum that allows us to choose which dis­tance we want to measure.

update method that calculates the distance between two points in unity
Fig. 5: Code of the Update method.

In the Start method, we find the ref­er­ence of the Line Ren­der­er assigned to the GameOb­ject camera.

In the Update method, we are going to do the cal­cu­la­tions, for this, we define two meth­ods “Cal­cu­late­Dis­tan­ceIn­Space” and “Cal­cu­late­Dis­tanceXY­Plane”, this last one takes into account only the X and Y com­po­nents of the objects as if the objects were pro­ject­ed in the XY plane, this is use­ful when we use the ortho­graph­ic view. In fig­ure 6 we can see these methods.

Arti­cle about “Meth­ods” in programming 

methods for calculating distances in unity
Fig. 6: Meth­ods for cal­cu­lat­ing dis­tances in space and in the plane.

MOST SEARCHED VIDEOS FROM MY CHANNEL

ABOUT UNITY

ABOUT BLENDER

Calculate distance between two objects in space — Vector3

Let’s start by look­ing at how to cal­cu­late the dis­tance between two objects in space, i.e. con­sid­er­ing the three dimen­sions of the scene.

The Cal­cu­late­Dis­tan­ceIn­Space method in Fig­ure 6 takes care of this. As you can see, the “Dis­tance” func­tion of the Vector3 class is used and we use the posi­tions of the objects as para­me­ters, this method will return the dis­tance between the two vectors.

Video 1: Dis­tance between two objects in space.

Calculate distance between two objects in the plane — Vector2

If we are work­ing in 2D or if we are inter­est­ed in know­ing the dis­tance between two objects pro­ject­ed on a plane, we can cal­cu­late this dis­tance using only two dimen­sions of the scene.

The Cal­cu­late­Dis­tan­ceInXY­Plane method in Fig­ure 6 takes care of this. As you can see, the Dis­tance method of the Vector2 class is used, two vec­tors are built using only the x and y com­po­nents of the posi­tion of the objects and they are passed as para­me­ters to the Dis­tance method of Vector2.

Video 2: Dis­tance between two objects in the plane. 

In the fol­low­ing video, we can see the dif­fer­ence between these two ways of cal­cu­lat­ing dis­tances between objects in Unity.

Video 3: Com­par­i­son of the dis­tance between two objects in the plane and in the space.

Conclusion

We have seen how to use the class­es Vector3 and Vector2 to cal­cu­late dis­tances between objects in space and in the plane respectively.

In gen­er­al Uni­ty works in 3D space, there­fore to mea­sure dis­tances in two dimen­sions it is nec­es­sary to project the points in some plane. We have to take into account that there are sev­er­al planes that we can use, in this case, we used the XY plane, but there is also the XZ, the YZ plane and we can even define a plane ori­ent­ed in any direction.

Appendix

Here you can see the com­plete script that cal­cu­lates the dis­tance between two objects in Unity.

script that calculates the distance between two vectors in unity
Fig. 7: Script Distances.

Базовые операции

Вывод сообщений в консоль

Debug.Log(“String First”);

Debug.Log(“String Second”);

Debug.Log(“String Third”);

Движение и вращение локально

Движение с учётом текущего угла поворота

transform.Translate(0, 0, speedMove * Time.deltaTime);

transform.Rotate(0, speedRotating * Time.deltaTime, 0);

Движение и вращение глобально

Движение в глобальном мире

transform.Translate(0, 0, speedMove * Time.deltaTime, Space.World);

transform.Rotate(0, speedRotating * Time.deltaTime, 0, Space.World);

Движение объекта в направление цели

GameObject targerGameObject = GameObject.Find(“Sphere”);

transform.position = Vector3.MoveTowards(transform.position, targerGameObject.transform.position, speed * Time.deltaTime);

Получение положения объекта

Vector3 pos = gameObject.transform.position;

string s = pos.x + ” ” + pos.y + ” ” + pos.z;

Получение расстояния между объектами

GameObject person_1 = gameObject;

GameObject person_2 = GameObject.Find(“Sphere”);

float d = Vector3.Distance(person_1.transform.position, person_2.transform.position);

Vector3 pos = GameObject.Find(“Sphere”).transform.position – transform.position;

Quaternion rotation = Quaternion.LookRotation(pos);

transform.rotation = rotation;

Получить угол поворота по оси Y

float yyy = gameObject.transform.rotation.y;

Изменение координат точки

Vector3 p = new Vector3(0, 0, 0);

gameObject.transform.position = p;

Сделать приложение во весь экран.

Screen.fullScreen = true;

На данном рисунке я попытался максимально изложить суть.
Изображение

введите сюда описание изображения

Черные стрелки – мировые координаты. Соответственно пытаюсь получить расстояние между объектами, а точнее разницу между координатами точки 1 и точки 2 с учетом их поворота.

задан 18 дек 2017 в 9:34

skDYLAN's user avatar

Случайно не это нужно: Vector3.Distance (или Vector2.Distance)?

var dist = Vector3.Distance(firstObject.position, secondObject.position);
DebugLog(dist);

ответ дан 18 дек 2017 в 9:59

Алексей Шиманский's user avatar

Алексей ШиманскийАлексей Шиманский

72.2k11 золотых знаков87 серебряных знаков172 бронзовых знака

8

Решение данной задачи заключается в следующем
Vector3 vec = obj1.GetComponent().InverseTransformDirection(obj2.GetComponent().position) – obj1.GetComponent().position;

ответ дан 18 дек 2017 в 12:23

skDYLAN's user avatar

2

[ad_1]

unity get distance between two objects

// Vector3.Distance is the same as (a-b).magnitude

float distance = Vector3.Distance(a.transform.position, b.transform.position);

how to compare distance between 2 objects unity

float distance = Vector3.Distance (object1.transform.position, object2.transform.position);

distance between two objects unity 2d

public GameObject object1;
public GameObject object2;
void Update()
{
  Vector2 Pos1 = object1.transform.position;
  Vector2 Pos2 = object2.transform.position;
  float x1 = Pos1.x, x2 = Pos2.x, y1 = Pos1.y, y2 = Pos2.y;
  // Distance between X coordinates
  float xDif = Mathf.Abs((Mathf.Max(x1,x2) - Mathf.Min(x1,x2));
  // Distance between Y coordinates
  float xDif = Mathf.Abs((Mathf.Max(y1,y2) - Mathf.Min(y1,y2));
  // Pythagorean theorem
  float finalDistance = Mathf.Sqrt(xDif * xDif + yDif * yDif);
  Debug.Log("Distance Between Object1 And Object2 Is " + finalDistance);
}

[ad_2]

Content Protection by DMCA.com

Добавить комментарий