Search code examples
c#unity-game-enginefloating-point

Difference between 0f and 0 on a Vector2 and Vector3 in Unity


Recenty started following a Unity tutorial and the script for the character controller is like this:

Vector2 inputVector = new Vector2(0, 0);

if (Input.GetKey(KeyCode.W)) {
    inputVector.y = +1;
}
if (Input.GetKey(KeyCode.S)) {
    inputVector.y = -1;
}
if (Input.GetKey(KeyCode.A)) {
    inputVector.x = -1;
}
if (Input.GetKey(KeyCode.D)) {
    inputVector.x = +1;
}

inputVector = inputVector.normalized;

Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
transform.position += moveDir;
Debug.Log(inputVector);

I understand that '0f' is so 0 is registered as a float rather than an integer but why is this needed in the Vector3 and not the Vector2 even though both of them require floats?

Thanks, RandomCodeEnjoyer


Solution

  • The constructors for Vector2 and Vector3 look like this:

    public Vector2(float x, float y);
    public Vector3(float x, float y, float z);
    

    Therefore, it doesn't matter at all how you specify the number: 0 or 0f. The number will still be converted to float.

    In which cases is it important to explicitly specify the type?

    1. Automatic deduce of the variable type:
    var x = 0f; // x is float
    
    1. Loss of precision in integer arithmetic:
    var i = 1;                          // i is int
    var v1 = new Vector2(i / 2,  0);    // v1.x = 0f
    var v2 = new Vector2(i / 2f, 0);    // v2.x = 0.5f
    
    1. The presence of several class constructors that accept arguments of different types (but it's more of a theory, no one does that):
    var v1 = new Vec2(0, 0);    // Vec2(int x, int y) is called
    var v2 = new Vec2(0, 0f);   // Vec2(float x, float y) is called
    var v3 = new Vec2(0f, 0f);  // Vec2(float x, float y) is called
    
    public class Vec2
    {
        public Vec2(int x, int y) => Console.WriteLine("Constructor for int");
        public Vec2(float x, float y) => Console.WriteLine("Constructor for float");
    }