Why is transform.Translate() swapping y and z?

I am trying to move a game object from where it is to the origin by calling:

transform.Translate( -transform.localPosition );

I printed out the local position before and after this call and here is the result:

Before: (0.0, -28.0, 8.0)
After: (0.0, -20.0, 36.0)

It looks like it’s adding z to the original y and adding -y to the original z. I have no idea why it’s not doing what it should and any help would be greatly appreciated. Thanks in advance.

Translate doesn’t swap anything. You’re using Transform.localPosition, which is relative to the parent, so that moves it to wherever the parent is, not the origin. (Unless it doesn’t have a parent, in which case it does move it to the origin.)

However that’s kind of a roundabout way of doing things anyway; it would be clearer to do “transform.position = transform.parent.position” to move to the parent’s position, or “transform.position = Vector3.zero” to move to the origin.

transform.Translate works by default in the objects local space. So when translating along the y axis it will move along it’s own local y axis.

Next thing is localPosition isn’t directly related to the objects local space. localPosition is a position in the local space of the parent object, if there is no parent then it’s relative to the world and the same as .position.

So you basically mixing two different coordinate spaces. localPosition will not change when you rotate the object in place, but Translate will move the object in a different direction since it uses the objects local space.

Like Eric said to move the object to 0,0,0 in the parent’s coordinate system, just set localPosition to Vector3.zero. If you want to move it to the world origin, set position to zero.

Translate has an optional “relativeTo” parameter which defaults to “Self” (the objects local space). You can pass “Space.World” to move relative to world space. However there’s no option to move in “parent space” or “parent.parent space”.

You can transform a point from localspace into worldspace by using TransformPoint of the transform that defines the localspace. For example this:

    var pos = transform.parent.TransformPoint(transform.localPosition);

is the same as:

    var pos = transform.position;

ps: An object is always located at 0,0,0 in it’s own localspace. Just to repeat it once more: localPosition is the position in the parent space.