# Unity Vector3 Guide for Newbies

## What is a Vector3

A vector is something that has direction and magnitude. In Unity, vectors are divided based on dimensions. A three-Dimensional vector is called Vector3. A vector3 contains the magnitude and direction information for all 3 dimensions. In game development Vector 3 is mostly used to find the position of an object and distance between objects. In this tutorial, we will see how to use Vector3 to its maximum potential.

## Syntax for Vector3

A Vector3 in Unity is represented by the name Vector3 followed by the magnitude along each axis.

``Vector3(1.0f,2.0f,-6.2f);``

By default, a Vector3 takes float as input. If you do not require the precision of float then you can specify the input as integer in the manner shown below.

``Vector3int(1,2,6);``

### Declaring a new Vector3

``Vector3 testvector=new Vector3(0,1,1);``

## Code samples for common examples.

### 1.Position of the Gameobject to which the script is attached.

``Vector3 Position= transform.position;``

### 2. Position of any Gameobject

``Vector3 Position= GameObject.Find("Your Gameobject name").transform.position;``

### 3. Move Gameobject by one unity using transform

``transform.position += vector3.one;``

### 4. Slowly move towards a point in steps of 1.

``````Vector3 target= new vector3(1f,2f,3f);
Void Update()
{
transform.position= Vector3.Movetowards(transform.position, target, 1.0f);

}``````

### 5. Slowly Look towards an Enemy

``````Void Start()
{
Vector3 Enemy_position= GameObject.Find("Enemy").transform.position;

}
Void Update()
{
Vector3 newDir = Vector3.RotateTowards(transform.forward, Enemy_position, 2*Time.deltaTime, 0.0f);
transform.rotation = Quaternion.LookRotation(newDir);
}
``````

You can also rotate slowly using Vector3.lerp

## Vector3 Project

Vector3.Project will project the provided vector onto the normal vector. Let’s try to understand this statement.

A normal vector is a Unit vector representing the direction of the vector. Say you have a vector 3 (10,5,3), if you normalize this you will get (1,1,1). If your vector is (0,10,0) the normalized output will be (0,1,0).

If you project the vector to its own normal then the output vector will be the same as the original.

Let’s take a Vector3 test_vec

``````Vector3 test_vec=new Vector3(10,5,0);
// Start is called before the first frame update
void Start()
{
Debug.Log(Vector3.Project(test_vec,Vector3.forward));

}
``````

Vector3.forward represents (0,0,1). So, the output vector will be (0,0,0).

If the normal vector is Vector3.up which is (0,1,0) the output will be (0,5,0)

If the normal vector is Vector3.Right which is (1,0,0) the output will be (10,0,0).

This site uses Akismet to reduce spam. Learn how your comment data is processed.