0% found this document useful (0 votes)
1 views

lecture 10 Maths

The document discusses the mathematical concepts of 2D and 3D vectors in game programming, particularly in Unity. It covers vector operations such as addition, subtraction, normalization, dot and cross products, and their applications in game mechanics like movement, targeting, and distance calculations. Additionally, it introduces interpolation methods like Lerp and Slerp for smooth transitions between points and directions in a game environment.

Uploaded by

Abdullah Azmat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

lecture 10 Maths

The document discusses the mathematical concepts of 2D and 3D vectors in game programming, particularly in Unity. It covers vector operations such as addition, subtraction, normalization, dot and cross products, and their applications in game mechanics like movement, targeting, and distance calculations. Additionally, it introduces interpolation methods like Lerp and Slerp for smooth transitions between points and directions in a game environment.

Uploaded by

Abdullah Azmat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

CS304: Game Programming

Lecture 10 Maths in Games


2D Vectors
A vector is a geometric object that has magnitude (or length) and direction.
In game world, allows to calculate forces, distances, relative angles between
objects, and the direction of an object

Vectors can be used to represent a point in space or a direction with a


magnitude. The magnitude of a vector can be determined by the magnitude
attribute. 2D Vectors in Unity have many properties and methods, and all of
them can be consulted in the reference:

http://docs.unity3d.com/ScriptReference/Vector2.h
tml
2D Vectors & Basic Geometry

2D vectors are composed of two components, (x, y ). For vectors starting at


the origin, these represent the distance from (0, 0) along the X and Y axis.
1 Vector2 vec =new Vector2 (1 ,2);
2 int x = vec .x; //1
3 int y = vec .y; //2

The length (or magnitude) of a vector is determined by its norm, calculated as


magnitude = ||vec || = \/x2 + y 2 . In Unity, the magnitude is available through
Vector2.magnitude attribute.
1 int magnitude = vec . magnitude ; //sqrt(5)=2.236...
Example: a vector could represent the speed at which an object moves. If the
vector is (2, 5), the object is moving 2 units per second in the X axis, and 5
units in the Y axis. The magnitude of the vector \ /22 + 52 = \/29 = 5.385 is
the linear speed of the object.
Operations on Vectors (1/5)

Addition: Scalar multiplication: Dot product:


a · b =b · a =
(1, 3) + (2, 2) = (3, 5) x(2, 3) = (2, 3)x = (2x, 3x)

a +b ≡ b + a 2(2, 3) = (4, 6) a · b = |a||b| cos(θ)

Subtraction: Negation: Cross product:

(4, 3) -(3, 1) = (1, 2) a = (3, 2), -a = (-3, -2) a xb = |a||b| sin(θ)n

a -b 6≡ b - a b = (2, -2), -b = (-2, 2) a xb ≡ -(b xa)


n is the unit vector perpendicular to
the plane containing a and b.
Operations on Vectors (2/5)
Operations on Vectors (3/5)

In Unity, you can use the normal operators for adding or subtracting to vectors,
and also for multiplying or dividing a vector by a number:
1 Vector2 a =new Vector2 (1 ,2);
2 Vector2 b =new Vector2 (3 ,4);
3 int val = 2;
4
5 Ve ct o r2 sum = a + b ;//or a-b
6 Vector2 mult = a * val;//or a/val

A unit vector is any vector with a length of 1; normally unit vectors are used
simply to indicate direction. A vector of arbitrary length can be divided by
its length to create a unit vector. This is known as normalizing a vector. A
vector can be normalized in Unity by calling the function public void Normalize
.1 Vector2 a =new Vector2 (1 ,2);
2 a. Normalize ();
3 Debug . Log (a. magnitude );//=1
Addition & Subtraction

Add: Vector3 sum = vectorA + vectorB;

Subtract: Vector3 difference = vectorA - vectorB;


Use Case: Moving or offsetting positions. For example, calculating an offset
position around an enemy to spawn another object nearby.

Example:
Vector3 spawnPosition = enemy.position + new Vector3(1, 0, 1);
Angle

Angle: Returns the angle in degrees between two vectors.


float angle = Vector3.Angle(vectorA, vectorB);

Use Case: Calculating the angle between two directions, helpful for
angle-based behaviors like aiming, targeting, or triggering events
based on angle thresholds.

Example:
float angle = Vector3.Angle(transform.forward, (target.position -
transform.position).normalized);
if (angle < maxViewAngle) {
// Target is within viewing angle
}
Magnitude

Vector3.Magnitude: Returns the length of the vector.


float length = vector3.magnitude;
Vector3.SqrMagnitude: Returns the squared length, which is faster to
compute and can be used for distance comparisons.
float sqrLength = vector3.sqrMagnitude;

Use Case: Measuring the length of a vector, such as a distance between two
points for range detection.

Example:
float distanceToTarget = (target.position - transform.position).magnitude;
if (distanceToTarget < attackRange) {
AttackTarget();
}
Normalize

Converts the vector to a unit vector (length of 1).


Vector3 normalizedVector = vector.normalized;

Use Case: Converting a direction vector to a unit vector for controlled


movement, such as making sure a player moves at a constant speed in a
specific direction.

Example:
Vector3 direction = (target.position - transform.position).normalized;
transform.position += direction * speed * Time.deltaTime;
Distance

Calculates the distance between two points.


float distance = Vector3.Distance(pointA, pointB);

Use Case: Calculating distance between objects, useful for proximity


checks or range-based actions.

Example:
float distance = Vector3.Distance(player.position, enemy.position);
if (distance < detectionRange)
{
AlertEnemy();
}
Operations on Vectors (4/5)
The Dot Product operation (sometimes called the inner product, or, since its
result is a scalar, the scalar product) is denoted as a · b = |a| x | b| x cos (θ),
where |a| and |b| are the magnitudes of a and b, and θ is the angle in radians
between these two vectors.
For normalized vectors, the dot product is 1 if they point in exactly the same
direction; -1 if they point in completely opposite directions; and a number in
between for other cases (e.g. Dot returns zero if vectors are perpendicular).

This is a useful operation that allows to determine the angle between two
vectors. This is very useful to determine the amount of rotation needed to
face certain position, angle of views, etc.
Dot product

Dot: Measures the angle between two vectors. If it’s close to 1, the
vectors point in the same direction; if -1, they are opposite.
float dotProduct = Vector3.Dot(vectorA, vectorB);

Use Case: Checking if two objects are facing the same direction (e.g.,
checking field of view for AI).

Example:
float dotProduct = Vector3.Dot(transform.forward, (target.position -
transform.position).normalized);
if (dotProduct > 0.5f) {
Debug.Log("Target is in front");
Operations on Vectors (5/5)

In Unity, you can use Vector2.Dot to calculate the dot product, calculate the
angle with Mathf.Acos(), and multiply the radians by Mathf.Rad2Deg to obtain the
angle in degrees.

1 Vector2 a =new Vector2 (0 ,5) ;


2 Vector2 b =new Vector2 (5 ,0) ;
3
4 a . N o rm a li ze
5 () ;//Forc on si s te ncy,n o rm al i zebo thv e ct o rs... b .
6 No rm a li ze () ;//...be fo rec a l c u l a t i n gitsdotp ro du ct.
7
8 Float do tP ro d uc t = V e ct o r2 . Dot (a , b ) ;
9 Debug . Log ("The dot product is: " + dotProduct );//=0
10
11 Float a ng l eR ad = M athf . Acos ( do tP ro du c t ) ; //thi sisarccos(x).
12 Debug . Log ("The angle is " + angleRad + " in radians .");//=1.5708
13
14 Float a ng l eD eg = a ng l eR ad * Mathf . Ra d 2D eg ;
Debug . Log ("The angle is " + angleDeg + " in degrees .");//=90
3D Vectors

A 3D vector is a geometric object that has magnitude (or length) and direc-
tion.

Vectors can be used to represent a point in space or a direction with a


magnitude. The magnitude of a vector can be determined by the magnitude
attribute. 3D Vectors in Unity have many properties and methods, and all of
them can be consulted in the reference:

http://docs.unity3d.com/ScriptReference/Vector3.h
tml
Operations with 3D vectors (1/4)

In Unity, you can use the normal operators for adding or subtracting to vectors,
and also for multiplying or dividing a vector by a number:
1 Vector3 a =new Vector3 (1 ,2 , -1);
2 Vector3 b =new Vector3 (3 ,4 ,0);
3 intval = 2;
4
5 Ve ct o r3 sum = a + b ;//ora-b
6 Vector3 mult = a * val;//ora/val

A unit vector is any vector with a length of 1; normally unit vectors are used
simply to indicate direction. A vector of arbitrary length can be divided by
its length to create a unit vector. This is known as normalizing a vector. A
vector can be normalized in Unity by calling the function public void Normalize
.1 Vector3 a =new Vector3 (1 ,2 , -7);
2 a. Normalize ();
3 Debug . Log (a. magnitude );//=1
Operations with 3D vectors (2/4)
Addition: Negation:

(1, 3, -1) + (2, 2, 0) = (3, 5, -1) a = (3, 0, -1), -a = (-3, 0, 1)

a +b ≡ b +a b = (2, -2, 3), -b = (-2, 2, -3)

Subtraction: Dot product:

(4, 3, 5) -(3, 1, 6) = (1, 2, -1) a · b = b · a n=

a -b 6≡ b - a a · b = |a| |b| cos(θ)

Scalar multiplication: Cross product:

x(2, 3, 1) = (2, 3, 1)x = (2x, 3x, 1x) a xb = |a| |b| sin(θ)n

2(2, 3, 2) = (4, 6, 4) a xb ≡ -(b xa)


n is the unit vector perpendicular to
the plane containing a and b.
Cross Product

Cross: Returns a vector perpendicular to the two input vectors, used


for determining the direction in 3D space.
Vector3 crossProduct = Vector3.Cross(vectorA, vectorB);

Use Case: Calculating a perpendicular vector for effects like camera


up vectors or determining the normal of a plane.

Example:
Vector3 up = Vector3.Cross(transform.right, transform.forward);
Operations with 3D vectors (3/4)
The Cross Product operation (also called vector product) is a binary operation
on two vectors in three-dimensional space, denoted as a x b = |a| |b| sin(θ)n.
The cross product a x b of the vectors a and b is a vector that is perpendicular
to both and therefore normal to the plane containing them. If the vectors have
the same direction or one has zero length, then their cross product is zero. You
can determine the direction of the result vector using the “right hand rule”.

1 Vector3 GetNormal ( Vector3 a, Vector3 b, Vector3 c) {


2 Vector3 side1 = c - a;
3 Vector3 side2 = b - a;
4 returnVector3 . Cross (side1 , side2 ). normalized ;
5 }
Operations with 3D vectors (4/4)
An example of use of the cross product is finding the axis around which to
apply torque in order to rotate a tank’s turret. With the direction the turret
is facing now, and the direction that it needs to face, the cross product gives
the vector to rotate around.

Cross product can also be used to determine the normal of a plane (i.e. a
triangle in a surface), in order to calculate directions for collisions and lighting.
Lerp

Linearly interpolates between from and to by the fraction t:


publicstatic Vector3 Lerp(Vector3 from, Vector3 to, float t);

This is most commonly used to find a point some fraction of the way along
a line between two endpoints (eg, to move an object gradually between those
points). This fraction is clamped to the range [0...1]. When t = 0 returns
from. When t = 1 returns to. When t = 0.5 returns the point midway between
from and to.
1 Transform target ;
2 Vector3 offset = transform . position - target . position ;
3 Vector3 targetCamPos = target . position + offset ;
4 floatsmoothing = 5f;
5
6 tr an s fo rm . p o si ti on = Ve c to r3 . Ler p ( tr a ns fo rm . po sitio n ,
7 ta rg e tC a mP o s , s m oo t hi ng * T ime .
de lt a Ti me ) ;
(There are equivalent functions in Mathf, Vector2, Color and
Material)
Lerp (Linear Interpolation)

Lerp: Interpolates between two vectors by a given


percentage/fraction t, where t is between 0 and 1.
Vector3 lerpResult = Vector3.Lerp(vectorA, vectorB, t);

Use Case: Smoothly interpolating between two points, such as


for camera movement or object transitions.
Example:
transform.position = Vector3.Lerp(transform.position,
target.position, Time.deltaTime * smoothing);
MoveTowards

Moves one vector towards another by a specified maximum


distance.
Vector3 newPosition = Vector3.MoveTowards(current, target,
maxDistanceDelta);

Use Case: Moving an object towards a target position at a fixed


rate, like a missile homing toward a target.
Example:
transform.position = Vector3.MoveTowards(transform.position,
target.position, speed * Time.deltaTime);
Slerp

Slerp (Spherical Linear Interpolation) (3D only)


Interpolates between two vectors over the surface of a sphere. Often
used for smooth rotations.
Vector3 slerpResult = Vector3.Slerp(vectorA, vectorB, t);

Use Case: Smoothly interpolating between two directions, often used


for camera rotations or for smoothly turning a character.
Example:
transform.rotation = Quaternion.Slerp(transform.rotation,
target.rotation, rotationSpeed * Time.deltaTime);
Clamp Magnitude

Clamp Magnitude
Limits the length of a vector to a maximum value.
Vector3 clampedVector = Vector3.ClampMagnitude(vector,
maxLength);

Use Case: Limiting the maximum speed of an object, such as


capping the player's speed to prevent excessive movement.
Example:
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
Smooth Damp
Public static Vector3.SmoothDamp(currentPosition, targetPosition, ref currentVelocity,
smoothTime, maxSpeed, deltaTime);
SmoothDamp is a Unity function that allows for smooth, gradual movement of
an object towards a target position, speed, or rotation with an easing effect. This
easing behavior is achieved by gradually reducing the speed as it approaches the
target, resulting in smooth, natural motion without sudden stops or changes. The
vector is smoothed by some spring-damper like function, which will never
overshoot.
current: The current position.
target: The position we are trying to reach.
currentVelocity: Current velocity, which value is modified by the function
at every call (to smoothly continue the movement in the next frame).
smoothTime: Approximately the time it will take to reach the target. A
smaller value will reach the target faster.
maxSpeed: Optionally allows you to clamp the maximum speed.
deltaTime: The time since the last call to this function. By default
Time.deltaTime.

1 transform . position = Vector3 . SmoothDamp ( transform . position ,


2 targetPosition ,ref velocity , 0.3 f);
(There are equivalent functions in Mathf and
Vector2)
Lerp vs SmoothDamp vs MoveTowards
Unity provides multiple ways to move an object smoothly from one point to
another: Lerp, SmoothDamp, and MoveTowards. Each has unique behavior
and is suited to different scenarios.
Lerp: Moves smoothly between two points based on t, and faster when closer
to end point
SmoothDamp: Moves smoothly between two points, but a bit fast in the middle
of both points and slows to a stop.
MoveTowards: Constant speed

You might also like