Transform.TransformPoint not working?

I’m not sure if I’m missing something here, but the following code does not give me the world position of my gameObject

Vector3 tmp = gameObject.transform.TransformPoint(gameObject.transform.localPosition);
Debug.Log(" tmp " + tmp.x + "," + tmp.y + "," + tmp.z);
Debug.Log(" gameObject.transform.position " + gameObject.transform.position.x + "," + gameObject.transform.position.y + "," + gameObject.transform.position.z);

The X and Y values are pretty much the same here, but the Z values are way different.

3 Answers

3

It seem the issue was caused by this script being placed on an object that was a child of a child. Referencing gameObject.transform.parent.TransformPoint resulted in the correct output.

It is not the solution. Referencing the parent of the parent of the parent is code smell. Function doesn't work as it described in documentation

If anyone else encounters this issue, I made a function that did what I expected transform.TransformPoint to do.

    // transforms position from local space to world space
    public static Vector3 TransformPoint(Transform t, Vector3 point)
    {
        return t.position
            + t.right * point.x
            + t.up * point.y
            + t.forward * point.z;
    }

transform.TransformPoint(Vector3.zero);
will give you the world position of the object.

So I’d say it makes sense that putting the local position of the object itself into the method will give you a different result.

TransformPoint will take a position relative to your Transform (like “something like 2m in front of me”) and return the world position equivalent (“I am at (0, 1, 0), and I am looking towards (0, 0, 1), so the thing is at (0, 1, 2).”).