Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. Mathf (Unity Math Library)

Mathf (Unity Math Library)

Since: C# 1.0(2002)

This page covers how to use Mathf, Unity's built-in math library. It is similar to C#'s Math class, but Mathf is specialized for float types and provides common game development utilities such as interpolation, clamping, and trigonometric functions.

Syntax

using UnityEngine;

// Returns the absolute value (float-specialized version).
float abs = Mathf.Abs(float f);

// Clamps a value between min and max.
float clamped = Mathf.Clamp(float value, float min, float max);

// Linearly interpolates from a to b by t (0–1).
float interpolated = Mathf.Lerp(float a, float b, float t);

// Trigonometric functions (argument is in radians).
float sin = Mathf.Sin(float f);
float cos = Mathf.Cos(float f);

// Converts degrees to radians.
float rad = degrees * Mathf.Deg2Rad;

// Converts radians to degrees.
float deg = radians * Mathf.Rad2Deg;

Method List

Method / ConstantDescription
Mathf.Abs(f)Returns the absolute value of f.
Mathf.Clamp(value, min, max)Returns value clamped to the range [min, max].
Mathf.Clamp01(value)Clamps value to [0, 1]. Convenient for normalizing values.
Mathf.Lerp(a, b, t)Linearly interpolates between a and b by t (0–1). Returns a when t=0, b when t=1.
Mathf.LerpUnclamped(a, b, t)Same as Lerp but does not clamp t to [0, 1]. Values outside the range are valid.
Mathf.Sin(f) / Mathf.Cos(f)Returns the sine / cosine of f (in radians).
Mathf.Sqrt(f)Returns the square root of f.
Mathf.Pow(f, p)Returns f raised to the power p.
Mathf.Floor(f) / Mathf.Ceil(f)Returns the floor / ceiling of f as a float.
Mathf.Round(f)Rounds f to the nearest integer.
Mathf.PIThe constant π (3.14159265...).
Mathf.Deg2RadConversion factor from degrees to radians (π / 180).
Mathf.Rad2DegConversion factor from radians to degrees (180 / π).
Mathf.InfinityPositive infinity constant.

Sample Code

A Unity MonoBehaviour sample combining Clamp, Lerp, and trigonometric functions.

MathfSample.cs
using UnityEngine;

public class MathfSample : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 5f;
    [SerializeField] private Transform target;

    void Start()
    {
        // Clamps HP to the range [0, 100].
        float hp = 120f;
        hp = Mathf.Clamp(hp, 0f, 100f);
        Debug.Log($"HP (clamped): {hp}"); // 100

        float diff = -3.5f;
        Debug.Log($"Abs: {Mathf.Abs(diff)}"); // 3.5

        // Calculates a sine wave for animation.
        float wave = Mathf.Sin(Time.time) * 2f;
        Debug.Log($"Sin value: {wave:F4}");

        // Converts degrees to radians.
        float degrees = 45f;
        float radians = degrees * Mathf.Deg2Rad;
        Debug.Log($"Sin(45°) = {Mathf.Sin(radians):F4}"); // 0.7071
    }

    void Update()
    {
        // Smoothly moves toward the target using Mathf.Lerp().
        if (target != null)
        {
            float t = moveSpeed * Time.deltaTime;
            transform.position = Vector3.Lerp(transform.position, target.position, t);
        }

        // Normalizes input to [0, 1] using Mathf.Clamp01().
        float input = Input.GetAxis("Horizontal");
        float normalized = Mathf.Clamp01(Mathf.Abs(input));
    }
}

Practical Pattern: Floating Animation with Sin Wave

A classic "floating" animation pattern that moves an object up and down using Mathf.Sin.

FloatingAnimation.cs
using UnityEngine;

public class FloatingAnimation : MonoBehaviour
{
    [SerializeField] private float amplitude = 0.5f; // Range of motion
    [SerializeField] private float frequency = 1f; // Frequency
    [SerializeField] private float rotateSpeed = 30f; // Rotation speed

    private Vector3 startPosition;

    void Start()
    {
        startPosition = transform.position;
    }

    void Update()
    {
        // Moves the object up and down along the Y axis using a sine wave.
        float yOffset = Mathf.Sin(Time.time * frequency) * amplitude;
        transform.position = startPosition + new Vector3(0f, yOffset, 0f);

        // Rotates around the Y axis.
        transform.Rotate(Vector3.up, rotateSpeed * Time.deltaTime);

        // Scales the object based on height (larger when higher).
        float scale = Mathf.Lerp(0.8f, 1.2f, (yOffset / amplitude + 1f) / 2f);
        transform.localScale = Vector3.one * scale;

        Debug.Log($"Y offset: {yOffset:F3}, Scale: {scale:F3}");
    }
}

Practical Pattern: SmoothStep and MoveTowards

SmoothStep provides smoother easing than Lerp, while MoveTowards moves at a constant speed without overshooting.

SmoothMovement.cs
using UnityEngine;

public class SmoothMovement : MonoBehaviour
{
    [SerializeField] private Transform destination;
    [SerializeField] private float speed = 2f;

    private float elapsedTime = 0f;
    private Vector3 startPos;

    void Start()
    {
        startPos = transform.position;
    }

    void Update()
    {
        if (destination == null) return;

        elapsedTime += Time.deltaTime;

        // SmoothStep: slow at start and end, fast in the middle (S-curve)
        float t = Mathf.Clamp01(elapsedTime / 3f);
        float smoothT = Mathf.SmoothStep(0f, 1f, t);
        transform.position = Vector3.Lerp(startPos, destination.position, smoothT);

        // MoveTowards: constant speed with a max-step limit (no overshoot)
        // transform.position = Vector3.MoveTowards(
        //     transform.position, destination.position, speed * Time.deltaTime);

        float distance = Vector3.Distance(transform.position, destination.position);
        Debug.Log($"Remaining: {distance:F2}m, Progress: {t:P0}");
    }
}

Common Mistakes

Common Mistake 1: Passing Degrees to Trigonometric Functions

Mathf.Sin / Mathf.Cos take radians. Passing degrees directly produces unexpected results.

using UnityEngine;

// NG: Intending to get sin(90°) but 90 radians is passed instead.
float wrongSin = Mathf.Sin(90f);
Debug.Log($"NG: {wrongSin:F4}"); // 0.8940 (not the expected 1.0)

// OK: Convert using Deg2Rad first.
float correctSin = Mathf.Sin(90f * Mathf.Deg2Rad);
Debug.Log($"OK: {correctSin:F4}"); // 1.0000

Common Mistake 2: Calling magnitude Every Frame in Update()

magnitude involves an internal Mathf.Sqrt (square root), which is expensive. For distance comparisons, use sqrMagnitude with the squared distance instead.

using UnityEngine;

public class MagnitudeNG : MonoBehaviour
{
    [SerializeField] private Transform target;
    private float attackRange = 5f;

    void Update()
    {
        if (target == null) return;

        // NG: magnitude includes Sqrt — expensive to call every frame.
        if ((target.position - transform.position).magnitude < attackRange)
            Debug.Log("In range (slow)");

        // OK: Compare sqrMagnitude with the squared distance — no Sqrt needed.
        if ((target.position - transform.position).sqrMagnitude < attackRange * attackRange)
            Debug.Log("In range (fast)");
    }
}

Overview

All Mathf functions operate on float types. C#'s Math class uses double, so Unity code generally uses Mathf instead. Trigonometric function arguments are in radians, not degrees. To pass a degree value, multiply by Mathf.Deg2Rad first.

When using Lerp() inside Update(), multiplying t by Time.deltaTime produces frame-rate-independent smooth interpolation. For vector math, see Vector2 / Vector3. For time-based animation using coroutines, see Coroutine / IEnumerator.

If you find any errors or copyright issues, please .