The cover for Unity: Get Distance Between Two Objects

Unity: Get Distance Between Two Objects

September 6, 2023

Introduction

I worked with my colleague yesterday to teach him how to calculate the distance between two points in a Visual Effect Graph. I dug around for some helpful resources online, but I found little. I wanted to make a comprehensive primer on how to get the distance between two objects in Unity.

In the world of game development, precision and accuracy are paramount. One crucial aspect is understanding how to measure the distance between objects in your Unity project. It doesn’t matter what type of game you’re making: a first-person shooter, a platformer, or a racing game. For any game, knowing the exact distance between objects is essential for various gameplay mechanics.

In this article, I will explain how to get the distance between two objects in Unity. I will explore different methods for getting the distance between two objects. You will learn C# Math C# Physics.Raycast, Visual Effect Graph, and Shader Graph.

This is a series on Unity Physics. We recommend reading the series in order.

  1. Unity Physics
  2. Unity Collision Detection
  3. Character Controller and Input Systems
  4. Rigidbody Mass in Unity
  5. How to add Friction to a Rigidbody
  6. Cylinder Collider in Unity
  7. Box Collider in Unity
  8. Box Cast in Unity
  9. Sorting Layers
  10. Get the distance between two objects
  11. How to normalize a vector

Introduction to Distance Measurement in Unity

Unity is a powerful game development engine. As such, it provides various tools and methods for measuring distances between objects. This measurement is crucial for enemy AI, object interaction, and collision detection tasks.

The most basic tool is the Vector3.Distance method. A more advanced technique is to calculate the distance yourself. You can also use the Physics ray cast system to test the physics distance.

Vector2.Distance, Vector3.Distance, and Vector4.Distance Declarations

Unity declared these static methods for you in the Vector2, Vector3, and Vector4 classes.

public static float Distance(Vector2 a, Vector2 b);
public static float Distance(Vector3 a, Vector3 b);
public static float Distance(Vector4 a, Vector4 b);

Vector3.Distance Usage

Most often, you will use Vector3. The same basic principles apply to all distance methods. The method expects two inputs, a and b. Each Vector parameter should be of the same Vector type.

Here’s how to use Vector3.Distance:

Vector3 a = Vector3.zero;
Vector3 b = Vector3.right;
float distance = Vector3.Distance(a, b);
Debug.Log(distance);

The Vector3 Class

Before we delve into distance measurement, let’s understand the Vector3 class in Unity. Vector3 represents a point or direction in 3D space. Developers use Vector3s for object positions.

Methods for Calculating Distance

Measure the Distance Between Two Objects Using Vector3.Distance()

The easiest way to measure the distance between two objects in Unity is with the Vector3.Distance() method. It calculates the Euclidean Distance between two points: the straight-line distance.

Get the Distance Using Math

You can manually calculate the distance between two objects using their positions. This approach gives you more control and customization. For example, you can apply a custom distance formula.

One way to calculate the distance manually is by using the magnitude. The magnitude represents the size or length of a vector. Learn more about Magnitude in my article on Vector normalization.

Vector3 a = Vector3.zero;
Vector3 b = Vector3.right;
float distance = (a-b).magnitude;
Debug.Log(distance);

The order of subtraction does not matter. The method is commutative.

Another way to calculate the distance is to do the entire math operation yourself.

Vector3 a = Vector3.zero;
Vector3 b = Vector3.right;
Vector3 c = b - a;
float distance = Mathf.Sqrt(c.x * c.x + c.y * c.y + c.z * c.z);
Debug.Log(distance);

If you’re comparing two distances, you can skip the Mathf.Sqrt calls. This approach helps provide minor savings on performance.

Measuring Distance in 2D Games

2D games need the same approach to distance measurement. But, in 2D games, you sometimes arrange objects on multiple sorting layers. Make sure that you account for those plane offsets when calculating the distance. You don’t need to worry if two are on the same plane.

Otherwise, it would help if you simulated that the two objects are on the same plane.

You can use Vector2.Distance for 2D games. Here’s an example. Suppose you have arranged your player and enemy on two different planes or layers. In this scenario, assume the player has a z position of 0, and the enemy has a z position of 5. You should ignore this z offset and constrain your comparison to the XY planes.

Vector2 a = new Vector2(player.position.x, player.position.y);
Vector2 b = new Vector2(enemy.position.x, enemy.position.y);
float distance = Vector2.Distance(a, b);
Debug.Log(distance);

Measuring distance using the Physics.Raycast() method

In this section, we will explore an advanced technique for distance evaluation. This technique uses the Physics.Raycast() method to return collisions that tell us about the distance to the nearest collider.

This method uses a Raycast to tell us if we hit something. If we hit something, we set the current distance to the distance to that collider. Then, we draw the ray using the OnDrawGizmos method.

using UnityEngine;

[ExecuteAlways]
public class UnityPhysicsRaycastDistance : MonoBehaviour
{
  [Min(0)]
  public float maxDistance = 10f;
  private float currentDistance = 10f;
  
  void Update()
  {
    currentDistance = maxDistance;
    if (
      Physics.Raycast(
        transform.position,
        transform.forward,
        out RaycastHit hitInfo,
        maxDistance
      )
    )
    {
      Debug.Log(hitInfo.distance);
      currentDistance = hitInfo.distance;
    }
  }
  
  private void OnDrawGizmos()
  {
    Gizmos.DrawRay(transform.position, transform.forward * currentDistance);
  }
}

You can use this script to debug Unity colliders and ray cast collisions. Learn more about Unity colliders in my comprehensive guide to Unity collisions.

Get Distance in VFX Graph

Visual Effect Graph is a flexible, node-based visual editor for Unity particle systems.

If you remember, my discussion with my coworker inspired this article. For that discussion, we wanted to kill a particle based on the distance to a target. So, we wanted to check the particle distance to a target position every frame.

VFX Graph makes it easy to get the distance here.

Use the Distance node with two Vector3 inputs to calculate the distance between the two inputs. You can use Vector2 or float, too. Be consistent.

Get Distance in Shader Graph

Shader Graph is another flexible, node-based visual editor for Unity. This one is for shaders.

Shader Graph also makes it easy to get the distance.

Use the Distance node with two Vector3 inputs to calculate the distance between the two. You can use Vector2 or float here, as well. Be consistent.

Understanding Units in Unity

Unity uses a unit system that relates to meters in the real world. You should always design your games around the 1 unit = 1 meter assumption. Otherwise, Unity physics and gravity will not work. When Unity returns a distance of '1’, that means '1 Unity unit’. If you designed your game well, this also means '1 in-game meter’.

Frequently Asked Questions

Is there a difference between measuring distance in 2D and 3D games?

Yes. The principles are the same. But 2D games need some adjustments to the calculation process. In 2D games, you must consider how you approach different depth layers.

Can I use distance measurements for pathfinding in Unity?

Yes. Distance measurements are crucial for pathfinding algorithms.

What’s the performance impact of frequent distance calculations?

Excessive calculations can impact performance. Use optimization techniques to mitigate this. I’ll give an example. You can use the squared distance for comparisons. The squared distance is faster than using the distance. It is faster because you can avoid a square root call.

Conclusion

In conclusion, you must understand how to get the distance between two objects in Unity. Using distance is a fundamental skill for creating engaging and interactive games.

In this comprehensive guide, I covered various methods and scenarios to evaluate distance.

You now know how to get the distance between two objects in C# using math, in C# using Physics, in Shader Graph, and in Visual Effect Graph.

So, you now have the tools you need to build better games.

To continue leveling up your skills, read our guide to using MoveTowards in Unity. Using MoveTowards is a fundamental skill for any developer.

Want to build better games?

© 2024