Back to Entitycomponentsystemsamples

Unity.Mathematics cheat sheet

EntitiesSamples/Docs/cheatsheet/mathematics.md

latest38.9 KB
Original Source
<!--- This file has been generated from mathematics.src.md Do not modify manually! Use the following tool: https://github.com/Unity-Technologies/dots-tutorial-processor -->

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

mathClass containing many static mathematical constants and methods.
noiseClass containing static methods for generating noise.
quaternionStruct representing a rotation.
RandomStruct for generating random numbers.
RigidTransformStruct representing a transform matrix.

Scalar types:

halfA 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

c#
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

c#
// 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:

c#
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.fmodThe floating point remainder of x/y.
math.madComponentwise (a * b + c) on three scalars or vectors.
math.modfModulus and fractional component.
math.csumHorizontal sum of components of a vector.
math.rcpReciprocal (1 divided by the value).

Exponents and logarithms

math.ceillog2Ceiling of the base-2 logarithm.
math.ceilpow2Smallest power of two greater than or equal to the input.
math.expThe constant e raised to a power.
math.exp10The value 10 raised to a power.
math.exp2The value 2 raised to a power.
math.floorlog2Floor of the base-2 logarithm.
math.logNatural logarithm.
math.log10Base-10 logarithm
math.log2Base-2 logarithm.
math.powRaised to a power.
math.rsqrtReciprocal of the square root.
math.sqrtSquare root.

Rounding and signs

math.absAbsolute value.
math.ceilRound up.
math.floorRound down.
math.roundRound to nearest.
math.signThe sign of a value: +1, 0 , or -1

Value checks

math.isfiniteIs finite floating-point value?
math.isinfIs infinite floating-point value?
math.isnanIs NaN?
math.ispow2Is power of 2?

Conversion

math.asdoubleReinterpret the bits of a 64-bit integer as a double.
math.asfloatReinterpret the bits of a 32-bit integer as a float.
math.asintReinterpret the bits of a float or uint as an int.
math.aslongReinterpret the bits of a double or 64-bit integer as a long.
math.asulongReinterpret the bits of a double or 64-bit integer as a ulong.
math.asuintReinterpret the bits of a float or uint as a uint.
math.f16tof32The floating point representation of a half-precision floating-point value.
math.f32tof16Nearest half-precision floating-point representation of a floating-point value.
math.fracFractional part of a floating-point value.
math.truncIntegral part of a floating-point value (rounded towards zero).

Interpolation and clamping

math.clampClamp a value into an interval.
math.lerpLinear interpolation between two values.
math.nlerpNormalized linear interpolation between two quaternions.
math.remapNon-clamping, linear remapping of a value from a source range to a destination range.
math.saturateClamp a value into the interval [0, 1].
math.slerpSpherical interpolation between two quaternions.
math.smoothstepSmooth Hermite interpolation between 0.0f and 1.0f.
math.stepReturn 1.0f if x >= y, otherwise returns 0.0f.
math.unlerpNormalize a value into a range. (Opposite of lerp.)

Picking between two values

math.shufflePick one or more specific components from two vectors.
math.selectPick between two values based on a boolean. Similar to the ternary operator, but you can also pick specific components of two vectors.
math.cmaxLargest component of a vector.
math.cminSmallest component of a vector.
math.maxLargest of two values.
math.minSmallest of two values.

Hashing

See the Collections package for more hashing options.

math.hashHash of a value.
math.hashwideWhen 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.allTrue if all booleans are true.
math.anyTrue if any boolean is true.
math.bitmaskBitmask of a bool4: one bit per component (4 bits in total) in LSB order (lower to higher).
math.countbitsCount of the 1-bits.
math.compressPacks mask-enabled components of a vector to the left.
math.lzcntLeading zero count of the bits.
math.reversebitsReverse the order of the bits.
math.rolRotate bits left.
math.rorRotate bits right.
math.tzcntTrailing zero count of the bits.

Trig, degrees, and radians

math.acosArccosine.
math.asinArcsine.
math.atanArctangent
math.atan2Arctangent for 2 arguments.
math.cosCosine.
math.coshHyperbolic cosine.
math.degreesDegrees from radians.
math.radiansRadians from degrees.
math.sinSine.
math.sincosSinecosine.
math.sinhHyberbolic sine.
math.tanTangent.
math.tanhHyberbolic tangent.

Vector geometry

math.crossCross product.
math.distanceDistance between two points (1 to 4 dimensions).
math.distancesqSquare root of distance between two points (1 to 4 dimensions).
math.dotDot product.
math.faceforwardFlips 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.lengthDistance of a point from the origin.
math.lengthsqSquare root of the distance of a point from the origin.
math.normalizeNormalized vector.
math.normalizesafeNormalized vector. Returns the default value if the normalized vector is not finite.
math.projectProject a vector on to another.
math.projectsafeProject a vector on to another. Returns the default value if the projected vector is not finite.
math.reflectReflection of an incident vector and a normal vector.
math.refractRefraction of an incident vector and a normal vector.
math.transformTransform a 3-dimensional vector with a 4x4 matrix.

Cardinal direction vectors

math.forwardThe forward axis in Unity coordinates.
math.backThe back axis in Unity coordinates.
math.upThe up axis in Unity coordinates.
math.downThe down axis in Unity coordinates.
math.leftThe left axis in Unity coordinates.
math.rightThe right axis in Unity coordinates.

Matrix ops

math.determinantDeterminant of a matrix.
math.fastinverseFast matrix inverse for rigid transforms (orthonormal basis and translation).
math.inverseInverse of a matrix or quaternion.
math.mulMatrix multiplication.
math.transposeTranspose of a matrix.
math.unitlogNatural logarithm of a unit length quaternion.

Rotations and transforms

math.conjugateConjugate a quaternion. (Flips the signs of x, y, and z but not w.)
math.orthonormalizeOrthonormalize a float3x3 matrix.
math.rotateRotate a vector by a unit quaternion.
math.unitexpNatural exponent of a quaternion. (Assumes w is zero.)
quaternion.AxisAngleQuaternion representation of an axis-angle rotation.
quaternion.EulerQuaternion representation of an Euler angle rotation (axis order specified by argument).
quaternion.EulerXYZQuaternion representation of an Euler angle rotation (axis order XYZ).
quaternion.EulerXZYQuaternion representation of an Euler angle rotation (axis order XZY).
quaternion.EulerYXZQuaternion representation of an Euler angle rotation (axis order YXZ).
quaternion.EulerYZXQuaternion representation of an Euler angle rotation (axis order YZX).
quaternion.EulerZXYQuaternion representation of an Euler angle rotation (axis order ZXY).
quaternion.EulerZYXQuaternion representation of an Euler angle rotation (axis order ZYX).
quaternion.LookRotationQuaternion representing a rotation derived from a unit-length forward vector and a unit-length upwards vector.
quaternion.LookRotationSafeQuaternion representing a rotation derived from a forward vector and an upwards vector.
quaternion.RotateXQuaternion representation of a rotation around the X axis.
quaternion.RotateYQuaternion representation of a rotation around the Y axis.
quaternion.RotateZQuaternion representation of a rotation around the Z axis.
float4x4.LookAtView matrix derived from an eye position, a target point, and a uni-length upwards vector.
float4x4.OrthoOrthographic projection matrix
float4x4.OrthoOffCenterOff-center orthographic projection matrix.
float4x4.PerspectiveFovPerspective projection matrix based on field of view.
float4x4.PerspectiveOffCenterOff-center perspective projection matrix
float4x4.ScaleMatrix representing a scale transform.
float4x4.TranslateMatrix representing a translation transform.
float4x4.TRSMatrix representing a combined translation, rotation, and scale transform.
float3x3.ScaleMatrix representing a scale transform.
RigidTransform.TranslateMatrix representing a translation transform.

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

Generating random numbers

c#
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.cellular2x22D Cellular noise ("Worley noise") with a 2x2 search window.
noise.cellular2x2x23D Cellular noise ("Worley noise") with a 2x2x2 search window.
noise.cnoiseClassic Perlin noise.
noise.pnoiseClassic Perlin noise, periodic variant.
noise.psrdoise2-D tiling simplex noise with fixed or rotating gradients and analytical derivative.
noise.psrnoise2-D tiling simplex noise with fixed or rotating gradients, but without the analytical derivative.
noise.snoiseSimplex noise.
noise.srdnoise2-D non-tiling simplex noise with fixed or rotating gradients and analytical derivative.
noise.srnoise2-D non-tiling simplex noise with fixed or rotating gradients, without the analytical derivative.