Math. Unity Math classes
Unity Math classes: Mathf, Random, Quaternion
Mathf
class
- Manual: Mathf class
- Script Reference: Mathf class
- Min, Max, Clamp, Abs: See Helpful Math functions
- See Interpolation (lerp, slerp…)
Trigonometric functions
- Sin, Cos, Tan, Asin, Acos, Atan, Atan2
- Rad2Deg, Deg2Rad
- PI
Other functions
- Pow, Sqrt, Exp, Log
- Abs
Limits & repeats
- Max, Min
- Clamp, Clamp01
- (value, min, max)
- Repeat, PingPong
- Ceil, Floor
- Mathf.DeltaAngle(a,b): Shortest difference between two given angles
Random
class
- Important classes: Random
- This page has all the random examples you need
- Script Reference: Random class
Random.Range
- Script Reference: Random.Range
- Note: For integers, the maximum value is exclusive (it’s not included!)
- For floats it’s inclusive (it IS included!)
- For example:
Random.Range(0,10)
returns random integer values $0,\dots,9$ (not $10$!)Random.Range(0f,10f)
returns random float values $0,\dots,10$
Quaternion
class
- Manual: Rotation and Orientation in Unity
- Euler angles are a rather simple way of representing rotation with three X,Y,Z values
- Quaternions: A four-dimensional extension of complex numbers with three imaginary axes
What you really need to know about Quaternions
- They’re used for representing rotation angles instead of Euler angles that can result in a gimbal lock
-
Most Unity devs don’t really need to understand the underlying maths
- Even though rotation is stored as a quaternion…
- four components: x, y, z, w
- …it is shown in Inspector with Euler angles
Quaternion note
- Never adjust Quaternion components independently, use ready-made functions from the Quaternion class
transform.rotation = Quaternion.LookRotation(target.position - transform.position)
transform.rotation = Quaternion.LookRotation(target.position - transform.position, new Vector3.Up)