Skip to content

Latest commit

 

History

History
449 lines (352 loc) · 38.9 KB

mathematics.md

File metadata and controls

449 lines (352 loc) · 38.9 KB

Unity.Mathematics cheat sheet

Most of the methods in Mathematics have many overloads for different combinations of types. For example, math.abs() takes vector arguments, not just scalars, e.g. math.abs(new int3(5, -7, -1)) returns new int3(5, 7, 1). This cheat sheet does not exhaustively demonstrate all of the overloads. Consult the API reference for the full list.

In this page:


Types

math Class containing many static mathematical constants and methods.
noise Class containing static methods for generating noise.
quaternion Struct representing a rotation.
Random Struct for generating random numbers.
RigidTransform Struct representing a transform matrix.

Scalar types:

half A 16-bit floating-point number.

Vector types:

bool2, bool3, bool4
int2, int3, int4
uint2, uint3, uint4
float2, float3, float4
half2, half3, half4
double2, double3, double4

Matrix types:

bool2x2, bool2x3, bool2x4, bool3x2, bool3x3, bool3x4, bool4x2, bool4x3, bool4x4
int2x2, int2x3, int2x4, int3x2, int3x3, int3x4, int4x2, int4x3, int4x4
uint2x2, uint2x3, uint2x4, uint3x2, uint3x3, uint3x4, uint4x2, uint4x3, uint4x4
float2x2, float2x3, float2x4, float3x2, float3x3, float3x4, float4x2, float4x3, float4x4
double2x2, double2x3, double2x4, double3x2, double3x3, double3x4, double4x2, double4x3, double4x4

Vector creation and copying

int4 i4 = new int4(1, 2, 3, 4);   // x, y, z, w
int2 i2 = int2.zero;              // new int2(0, 0);

// Index the components like an array.
int i = i4[2];                    // int i = i4.z
i4[0] = 9;                        // i4.x = 9

// Creating a vector by copying combinations
// of values from another vector (swizzling).
i4 = i4.xwyy;                     // new int4(i4.x, i4.w, i4.y, i4.y);
i2 = i4.yz;                       // new int2(i4.y, i4.z);
i4 = i2.yxyx;                     // new int4(i2.y, i2.x, i2.y, i2.x);

// Creating a vector from combinations of
// lower-dimension vectors and scalars.
i4 = new int4(1, i2, 3);          // new int4(1, i2.x, i2.y, 3);
i4 = new int4(i2, i2);            // new int4(i2.x, i2.y, i2.x, i2.y);
i4 = new int4(7);                 // new int4(7, 7, 7, 7);
i2 = new int2(7.5f);              // new int2((int) 7.5f, (int) 7.5f);

// Creating a vector by casting.
i4 = (int4) 7;                    // new int4(7, 7, 7, 7);
i2 = (int2) 7.5f;                 // new int2((int) 7.5f, (int) 7.5f);

Matrix creation and copying

// Values in row-major order.
int2x3 m = new int2x3(1, 2, 3, 4, 5, 6);    // first row: 1, 2, 3
                                            // second row: 4, 5, 6

// First column: new int2(1, 4)
int2 i2 = m.c0;

// Third column: new int2(3, 6)
i2 = m.c2;

// new int2x3(100, 100, 100, 100, 100, 100)
m = new int2x3(100);

m = new int2x3(
    new int2(1, 2),   // column 0
    new int2(3, 4),   // column 1
    new int2(5, 6));  // column 2

// Converts each int component to a float.
float2x3 m2 = new float2x3(m);

Vector and matrix operators

The vector and matrix operators (+, -, *, /, %, --, ++, ==, !=, <, >, <=, >=) operate upon corresponding component pairs:

int2 a = new int2(1, 2);
int2 b = new int2(3, 4);

// Addition.
int2 c = a + b;               // new int2(a.x + b.x, a.y + b.y)

// Negation.
c = -a;                       // new int2(-a.x, -a.y)

// Equality.
bool myBool = a.Equals(b);    // a.x == b.x && a.y == b.y
bool2 myBool2 = a == b;       // new int2(a.x == b.x, a.y == b.y)

// Greater than.
myBool2 = a > b;              // new bool2(a.x > b.x, a.y > b.y)

The integer vector and matrix types also have bitwise operators: &, |, ~, <<, >>.


Arithmetic

math.fmod The floating point remainder of x/y.
math.mad Componentwise (a * b + c) on three scalars or vectors.
math.modf Modulus and fractional component.
math.csum Horizontal sum of components of a vector.
math.rcp Reciprocal (1 divided by the value).

Exponents and logarithms

math.ceillog2 Ceiling of the base-2 logarithm.
math.ceilpow2 Smallest power of two greater than or equal to the input.
math.exp The constant e raised to a power.
math.exp10 The value 10 raised to a power.
math.exp2 The value 2 raised to a power.
math.floorlog2 Floor of the base-2 logarithm.
math.log Natural logarithm.
math.log10 Base-10 logarithm
math.log2 Base-2 logarithm.
math.pow Raised to a power.
math.rsqrt Reciprocal of the square root.
math.sqrt Square root.

Rounding and signs

math.abs Absolute value.
math.ceil Round up.
math.floor Round down.
math.round Round to nearest.
math.sign The sign of a value: +1, 0 , or -1

Value checks

math.isfinite Is finite floating-point value?
math.isinf Is infinite floating-point value?
math.isnan Is NaN?
math.ispow2 Is power of 2?

Conversion

math.asdouble Reinterpret the bits of a 64-bit integer as a double.
math.asfloat Reinterpret the bits of a 32-bit integer as a float.
math.asint Reinterpret the bits of a float or uint as an int.
math.aslong Reinterpret the bits of a double or 64-bit integer as a long.
math.asulong Reinterpret the bits of a double or 64-bit integer as a ulong.
math.asuint Reinterpret the bits of a float or uint as a uint.
math.f16tof32 The floating point representation of a half-precision floating-point value.
math.f32tof16 Nearest half-precision floating-point representation of a floating-point value.
math.frac Fractional part of a floating-point value.
math.trunc Integral part of a floating-point value (rounded towards zero).

Interpolation and clamping

math.clamp Clamp a value into an interval.
math.lerp Linear interpolation between two values.
math.nlerp Normalized linear interpolation between two quaternions.
math.remap Non-clamping, linear remapping of a value from a source range to a destination range.
math.saturate Clamp a value into the interval [0, 1].
math.slerp Spherical interpolation between two quaternions.
math.smoothstep Smooth Hermite interpolation between 0.0f and 1.0f.
math.step Return 1.0f if x >= y, otherwise returns 0.0f.
math.unlerp Normalize a value into a range. (Opposite of lerp.)

Picking between two values

math.shuffle Pick one or more specific components from two vectors.
math.select Pick between two values based on a boolean. Similar to the ternary operator, but you can also pick specific components of two vectors.
math.cmax Largest component of a vector.
math.cmin Smallest component of a vector.
math.max Largest of two values.
math.min Smallest of two values.

Hashing

See the Collections package for more hashing options.

math.hash Hash of a value.
math.hashwide When hashing multiple values together, it's often more efficient to separately pass them to hashwide(), combine the results, then hash() the combination.

Bitwise and boolean operations

math.all True if all booleans are true.
math.any True if any boolean is true.
math.bitmask Bitmask of a bool4: one bit per component (4 bits in total) in LSB order (lower to higher).
math.countbits Count of the 1-bits.
math.compress Packs mask-enabled components of a vector to the left.
math.lzcnt Leading zero count of the bits.
math.reversebits Reverse the order of the bits.
math.rol Rotate bits left.
math.ror Rotate bits right.
math.tzcnt Trailing zero count of the bits.

Trig, degrees, and radians

math.acos Arccosine.
math.asin Arcsine.
math.atan Arctangent
math.atan2 Arctangent for 2 arguments.
math.cos Cosine.
math.cosh Hyperbolic cosine.
math.degrees Degrees from radians.
math.radians Radians from degrees.
math.sin Sine.
math.sincos Sinecosine.
math.sinh Hyberbolic sine.
math.tan Tangent.
math.tanh Hyberbolic tangent.

Vector geometry

math.cross Cross product.
math.distance Distance between two points (1 to 4 dimensions).
math.distancesq Square root of distance between two points (1 to 4 dimensions).
math.dot Dot product.
math.faceforward Flips a vector if two other vectors point in the same direction (i.e. the angle between them is less than or equal to 90 degrees).
math.length Distance of a point from the origin.
math.lengthsq Square root of the distance of a point from the origin.
math.normalize Normalized vector.
math.normalizesafe Normalized vector. Returns the default value if the normalized vector is not finite.
math.project Project a vector on to another.
math.projectsafe Project a vector on to another. Returns the default value if the projected vector is not finite.
math.reflect Reflection of an incident vector and a normal vector.
math.refract Refraction of an incident vector and a normal vector.
math.transform Transform a 3-dimensional vector with a 4x4 matrix.

Cardinal direction vectors

math.forward The forward axis in Unity coordinates.
math.back The back axis in Unity coordinates.
math.up The up axis in Unity coordinates.
math.down The down axis in Unity coordinates.
math.left The left axis in Unity coordinates.
math.right The right axis in Unity coordinates.

Matrix ops

math.determinant Determinant of a matrix.
math.fastinverse Fast matrix inverse for rigid transforms (orthonormal basis and translation).
math.inverse Inverse of a matrix or quaternion.
math.mul Matrix multiplication.
math.transpose Transpose of a matrix.
math.unitlog Natural logarithm of a unit length quaternion.

Rotations and transforms

math.conjugate Conjugate a quaternion. (Flips the signs of x, y, and z but not w.)
math.orthonormalize Orthonormalize a float3x3 matrix.
math.rotate Rotate a vector by a unit quaternion.
math.unitexp Natural exponent of a quaternion. (Assumes w is zero.)
quaternion.AxisAngle Quaternion representation of an axis-angle rotation.
quaternion.Euler Quaternion representation of an Euler angle rotation (axis order specified by argument).
quaternion.EulerXYZ Quaternion representation of an Euler angle rotation (axis order XYZ).
quaternion.EulerXZY Quaternion representation of an Euler angle rotation (axis order XZY).
quaternion.EulerYXZ Quaternion representation of an Euler angle rotation (axis order YXZ).
quaternion.EulerYZX Quaternion representation of an Euler angle rotation (axis order YZX).
quaternion.EulerZXY Quaternion representation of an Euler angle rotation (axis order ZXY).
quaternion.EulerZYX Quaternion representation of an Euler angle rotation (axis order ZYX).
quaternion.LookRotation Quaternion representing a rotation derived from a unit-length forward vector and a unit-length upwards vector.
quaternion.LookRotationSafe Quaternion representing a rotation derived from a forward vector and an upwards vector.
quaternion.RotateX Quaternion representation of a rotation around the X axis.
quaternion.RotateY Quaternion representation of a rotation around the Y axis.
quaternion.RotateZ Quaternion representation of a rotation around the Z axis.
float4x4.LookAt View matrix derived from an eye position, a target point, and a uni-length upwards vector.
float4x4.Ortho Orthographic projection matrix
float4x4.OrthoOffCenter Off-center orthographic projection matrix.
float4x4.PerspectiveFov Perspective projection matrix based on field of view.
float4x4.PerspectiveOffCenter Off-center perspective projection matrix
float4x4.Scale Matrix representing a scale transform.
float4x4.Translate Matrix representing a translation transform.
float4x4.TRS Matrix representing a combined translation, rotation, and scale transform.
float3x3.Scale Matrix representing a scale transform.
RigidTransform.Translate Matrix representing a translation transform.

RigidTransform, float3x3, and float4x4 also have most of the same rotation methods as quaternion.


Generating random numbers

Random rand = new Random(123);  // seed of 123

// [-2147483647, 2147483647]
int integer = rand.NextInt();

// [25, 100)
integer = rand.NextInt(25, 100);

// x is [0, 1), y is [0, 1)
float2 f2 = rand.NextFloat2();

// x is [0, 7.5), y is [0, 11)
f2 = rand.NextFloat2(new float2(7.5f, 11f));

// x is [2, 7.5), y is [-4.6, 11)
f2 = rand.NextFloat2(new float2(2f, -4.6f) , new float2(7.5f, 11f));

// Uniformly random unit-length direction vector.
double3 d3 = rand.NextDouble3Direction();

// Uniformly random unit-length quaternion.
quaternion q = rand.NextQuaternionRotation();

// Create multiple Random number generators using an incremented seed.
NativeArray<Random> rngs = new NativeArray<Random>(10, Allocator.Temp);
for (int i = 0; i < 10; i++)
{
    // Unlike the Random constructor, CreateFromIndex hashes the seed.
    // If we were to pass incremented seeds to the constructor,
    // each RNG would produce a similar stream of random numbers
    // as each other. Because we instead here use CreateFromIndex,
    // the RNG's will each produce streams of random numbers that
    // are properly distinct and unrelated to the others.
    rngs[i] = Random.CreateFromIndex((uint)(i + 123));
}

Generating noise

noise.cellular(float2) 2D Cellular noise ("Worley noise") with standard 3x3 search window for good feature point values.
noise.cellular(float3) 3D Cellular noise ("Worley noise") with 3x3x3 search region for good F2 everywhere, but a lot slower than the 2x2x2 version.
noise.cellular2x2 2D Cellular noise ("Worley noise") with a 2x2 search window.
noise.cellular2x2x2 3D Cellular noise ("Worley noise") with a 2x2x2 search window.
noise.cnoise Classic Perlin noise.
noise.pnoise Classic Perlin noise, periodic variant.
noise.psrdoise 2-D tiling simplex noise with fixed or rotating gradients and analytical derivative.
noise.psrnoise 2-D tiling simplex noise with fixed or rotating gradients, but without the analytical derivative.
noise.snoise Simplex noise.
noise.srdnoise 2-D non-tiling simplex noise with fixed or rotating gradients and analytical derivative.
noise.srnoise 2-D non-tiling simplex noise with fixed or rotating gradients, without the analytical derivative.