Absolute Value in Unity: A Comprehensive Overview

by Michael Sacco Published August 23, 2023
The cover for Absolute Value in Unity: A Comprehensive Overview

As a Unity developer, you must have heard of an "absolute value". As a beginner, it is easy to get confused by it. This is a common problem. You are not alone. The absolute value is a fundamental mathematical concept. It is not as complex as it may sound. In this article, we will explain what the absolute value is. And, we will show you how to use it in your game.

:::info What you need to know

  • Absolute value is a basic math concept.
  • You use this concept to measure how far a number is from zero.
  • The absolute value can make some calculations easier.
  • Use Mathf.Abs() for floats and integers.
  • Use my extension method for Vectors.

:::

What is an absolute value?

The absolute value of a number is its distance from zero on the number line. When the number is positive, the absolute value is positive. When the number is negative, the absolute value is also positive. Whether the number is positive or negative, the absolute value is always positive. For example, the absolute value of ‘5’ is ‘5’. And, the absolute value of ‘-5’ is also ‘5’. This is because both ‘5’ and ‘-5’ are 5 units away from ‘0’.

When can I use the absolute value?

In Unity game development, you can use absolute value to simplify some operations. I will give you some examples.

  • Guarantee that an object scale is always positive.
  • Determine the error between predicted and actual values.
  • Calculate the size of an input value.

Some practical examples of using absolute value in Unity

In this section, I will go through some practical examples for absolute value. These examples should help you understand how to use the absolute value in your project.

Compare the distance between one object and another

The distance between two objects will always be a positive number. You can use the absolute value to calculate the distance between two objects. For example, Mathf.Abs(positionA - positionB). In this case, you don’t need a signed result. So, using the absolute value guarantees that you get a positive result every time.

Trigger gameplay events based on the size of a change

You can use the absolute value to calculate the size of a value. When you apply a damage (-5) or healing (+3) effect to a character, the value may be negative or positive. You can calculate the size of this effect. Then, you can use the size of the effect as a gameplay trigger. Let’s say that you want to give a player bonus if they take a lot of damage. You also want to give them the same bonus if they take a lot of healing. You can use the absolute value to check if the size of the damage or healing meets your threshold.

How do I get the absolute value?

To calculate the absolute value of a scalar in Unity, use the Mathf.Abs() function.

To use the function, you pass the input value as the parameter.

Then, the function returns the absolute value of the input parameter.

Here’s a simple example in code:


float originalValue = -7.5f;

float absoluteValue = Mathf.Abs(originalValue);

In this example, absoluteValue will hold the value 7.5. This is true even though the original value was negative.

How do I get the absolute value of a vector?

You need to calculate the absolute value for the vector. To do that, you need to understand how a vector works. A vector is made up of parts. We call each part of a vector a component. A Vector3 has three components: x, y, and z. A Vector2 has two components: x and y.

Unity did not include a Vector3.Abs() function. So, we have to calculate it ourselves.


Vector3 originalVector = new Vector3(-2.0f, 3.5f, -1.8f);

Vector3 absoluteVector = new Vector3(Mathf.Abs(originalVector.x), Mathf.Abs(originalVector.y), Mathf.Abs(originalVector.z));

In this example, our original vector has three components. The x and z components are negative. The y component is positive.

Then, we take the absolute value of each component. Once we do that, the x, y, and z components are all positive.

:::note Try it yourself

Can you guess the new value of the x, y, and z components?

:::

Is there an easier way to get the absolute value of a vector?

Yes. I wrote an extension method for you. You can add this method to your project. Then, call it with your vector.

Here’s the extension method. Copy and paste this into a new script in your project.


using UnityEngine;



public static class MyExtensions

{

    public static Vector2 Abs(this Vector2 vector)

    {

        return new Vector2(Mathf.Abs(vector.x), Mathf.Abs(vector.y));

    }



    public static Vector3 Abs(this Vector3 vector)

    {

        return new Vector3(Mathf.Abs(vector.x), Mathf.Abs(vector.y), Mathf.Abs(vector.z));

    }



    public static Vector4 Abs(this Vector4 vector)

    {

        return new Vector4(

            Mathf.Abs(vector.x),

            Mathf.Abs(vector.y),

            Mathf.Abs(vector.z),

            Mathf.Abs(vector.w)

        );

    }

}

To use it, create a new vector. Then, call `vector.Abs()` and save the result.


using UnityEngine;



public class VectorAbsExample : MonoBehaviour

{

    void Start()

    {

        Vector3 vector = new Vector3(-1, 0, 0);

        Debug.Log(vector.Abs());

        Debug.Log(vector);

    }

}

How do I calculate the length of a vector?

To calculate the length of a vector, use the .magnitude property.

It is important that you do not confuse the length with the absolute value. The length is different from the absolute value of a vector.

The length is a single, scalar value. That value is also known as the magnitude.

The absolute value keeps each component of the vector. But, we apply the absolute value to each component.

Try using absolute value in your project

You should have a good understanding of absolute value in Unity. Now, it is time to apply yourself.

Step 1: Create a simple 2D game

Create a simple 2D game. In this game, the player controls a character. The character can only move left or right. You can also jump. Your character encounters obstacles. As the player, you need to jump over the obstacle. The game will award points for jumping over the obstacle.

Step 2: Assign points for each obstacle

The game bases the number of points on the distance of the obstacle from x = 0. Here’s a breakdown:

  • An obstacle at x = 5 awards 5 points.
  • An obstacle at x = -5 also awards 5 points.
  • An obstacle at x = 10 awards 10 points.

Use the absolute value to calculate the number of points that the obstacle should award.

To approach this problem, you can break it down into two steps.

Calculate the Distance:

Use the Mathf.Abs() function. Calculate the absolute distance to the obstacle. Use the start position of the player and the position of the obstacle. e.g., Mathf.Abs(playerPosition - obstaclePosition);

Award Points

Create a system that awards points to the player. Use the distance as the basis for the number of points. Award more points when the player jumps over obstacles that are far away. Award less points when the player jumps over obstacles that are nearby.

Recommended reading

Start with the Unity docs to review your understanding of Mathf.Abs().

Then, check out this Unity forum thread so that you don’t feel so alone.

Finally, read this interesting blog post on the many ways to take the absolute value in Unity.

To continue learning the basics of Unity for beginners, read my article on global variables in Unity.

Free download: Indie Game Marketing Checklist

Download now

Category

unity basics

Don't forget to share this post!

Popular assets for Unity

See all assets ->
    Cutting-edge volumetric fog and volumetric lighting with support for transparent materials.
    Volumetric clouds, day night cycles, dynamic skies, global lighting, weather effects, and planets and moons.
    A lightweight procedural skybox ideal for semi-stylized projects.
    Image-based Outlines for 2D and 3D games with variable line weight, color, and displacement options.
    Drag-and-drop ready-to-use ambient, impact, and spell particle effects.
    Per-pixel gaussian blur on your entire screen, part of the UI, or in-scene objects.

Free Indie Game Marketing Checklist

Learn how to make your game successful with this handy checklist.

Download for free