# Unity C# Beginner Tutorial | How to Calculate Direction & Distance in 3D

In this story, I’m going to show you the idea behind how to get direction in Unity. Every position in 3d space is a vector. So in Unity, Vector3 is the representation of 3D vectors and points thus every gameobject in Unity has its vector position in 3d space.

We can use these vectors to calculate everything in our 3d spaces. In our case, we want to get the direction. For example, if we want to get the direction or distance of the enemy from our position. How can we calculate the direction of CubeB(green) from Cube A(red)?

### Idea

As we know that everything in 3d space has its vector position.

It’s a coordinate system.

This is how we can get the direction and distance of a vector, it’s Pythagoras Theorem.

In our case, it should be distance² = 7² + 4² + 11². Then distance = Square root(7² + 4 ² + 11²).

This is just the idea behind the calculation, but in Unity when don't have to calculate everything manually. It’s done by the engine. It’s way easier than that.

### Code

So how can we calculate the direction of these two game objects in Unity? The formula is this: Direction = Destination-Source

Here is a simple script to get the direction of two game objects.

#### Variables

• target: the position of the target gameobject you want to get

#### Update method

• Vector3 direction: vector3 variable to save the target direction value
• transform.position: the position of this gameobject(the gameobject which you put this script in. )
• Vector3 direction = target.position-transform.position: this is the formula. We subtract the vector position of this gameobject (Cube A) from the target vector position (Cube B) and store the value in the direction variable.

### Real situation example

This is also useful if you want to know the distance between a gameobject, or if you want to create an enemy system where it chases the player! In this example, once we have the direction we can make Cube A move to the target.