This is a 2D vector
Vectors start from the origin, or
In C#:
Vector2 vectorA = new Vector2(6,3);
The length of a 2D vector is given by the Pythagoras theorem
In C#:
float length = Mathf.Sqrt(Mathf.Pow(vectorA.x, 2) + Mathf.Pow(vectorA.y, 2));
A.magnitude
sum of two vectors is calculated by summing up the individual components
can be illustrated by moving
Vector2 A = new Vector2(3.0f, 3.0f);
Vector2 B = new Vector2(6.0f,-2.0f);
Vector2 C = A + B;
difference of two vectors,
Vector2 A = new Vector2(3.0f, 3.0f);
Vector2 B = new Vector2(6.0f,-2.0f);
Vector2 C = A - B;
When a vector is multiplied by a scalar (a number), the vector is scaled
Vector2 A = new Vector2(3.0f,3.0f);
Vector2 C = 2 * A;
If the scalar is negative, the vector gets flipped
What about division?
Unity has two Vector classes, Vector2 and Vector3
Vector2 position = new Vector2(1.0f, 2.0f)
Vector components can be accessed with the dot notation:
position.x
, position.y
, position.z
Vectors can't be directly modified:
position.x = 3.0f
position = new Vector2(3.0f, position.y);
Length of a vector can be acquired with vector.magnitude
new_position = old_position + velocity;
Update()
method:
transform.position += velocity;
Note: Velocity vector is usually drawn so it starts from the moving object
(Remember, though, that vectors do not "know" its starting positions.)
new_velocity = old_velocity + acceleration
;rb.velocity += acceleration
;velocity += acceleration;
transform.position += velocity;
vector_B - vector_A
transform.position - otherGameObject.transform.position;
Vector2.Distance(vector_A, vector_B)
Vector3.right
: the global Vector3.up
: the global Vector3.forward
: the global Vector2 UnitVector = A.normalized;
Vector3 rotatedVector = Quaternion.Euler(0, 0, 90) * originalVector;
myQuaternion *= Quaternion.Euler(0, 0, 90);
Vector3.Dot
returns
float alignment = Vector3.Dot(
_rigidBody.velocity.normalized,
otherGameObjectRigidBody.velocity.normalized)
.sqrMagnitude
instead!Create a scene with two GameObjects, a player and a static enemy.
Calculate the distance between the player and the enemy.
If the distance is smaller than some given threshold value,