Home > Blockchain >  y component of Vector3 doesn't match
y component of Vector3 doesn't match

Time:10-09

I have this coroutine to calculate the velocity

    IEnumerator CalcVelocity()
    {
            prevPos = transform.position;
            yield return new WaitForEndOfFrame();
            print(((prevPos - transform.position) / Time.deltaTime));
            print(((prevPos - transform.position) / Time.deltaTime).y);
            velocity = Mathf.Abs(((prevPos - transform.position) / Time.deltaTime).y);
    }

I'm printing out the velocity in all directions and then the y velocity as that's the only I need for my purpose.

However sometimes the serialized Vector3 and the y component don't match - as below they are wildly different. The y value seems to be completely wrong.

(0.0, 0.0, 0.0) // the Vector3 printout

8.488064E-05 // the y

What's gone wrong here?

CodePudding user response:

What's gone wrong here? Nothing, it's just how unity show things in your log

If you run this

public void Test()
{
    var v = new Vector3(0f, 0.00001f, 0f);
    var y = v.y;
    
    Debug.Log($"{v}");
    Debug.Log($"{y}");
}

You will see this enter image description here

If you want to see more than 1 decimal, you can use formatters

public void Test()
{
    var v = new Vector3(0f, 0.00001f, 0f);
    var y = v.y;
    
    Debug.Log($"{v.ToString("F5")}");
    Debug.Log($"{y}");
}

enter image description here

N

CodePudding user response:

Nothing is wrong.

The default implementation of Vector3.ToString uses a human readable rounded display (see source code)

    public override string ToString()
    {
        return ToString(null, CultureInfo.InvariantCulture.NumberFormat);
    }

    public string ToString(string format)
    {
        return ToString(format, CultureInfo.InvariantCulture.NumberFormat);
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        if (string.IsNullOrEmpty(format))
            format = "F1";
        return UnityString.Format("({0}, {1}, {2})", x.ToString(format, formatProvider), y.ToString(format, formatProvider), z.ToString(format, formatProvider));
    }

As you can see by default it uses "F1" meaning fixed floating point format rounded to a single decimal.

You can provide any custom format you want like e.g.

print(((prevPos - transform.position) / Time.deltaTime).ToString("G9"));

Where "G" is the general formatter allowing to either print scientific or fixed point presentation depending on which one is more compact.

By chosing G9 it ensures that the float values are printed and then if they would get parsed again would always successfully roundtrip without any data loss.

For more information about available formatting strings see Standard Numeric Format Strings and Custom Format Strings

  • Related