[Unity] Why Transform.Translate doesn’t move the expected distance.

This article can be read in about 4 minutes.
PR

The purpose

Transform.Translate didn’t move the expected distance in Unity. I’ll investigate what’s happening and provide solutions.

I will now be discussing the movement amount in a single call. If you’re encountering unintended behavior when calling this repeatedly in Update or FixedUpdate, please refer to the section below. You’ll need to account for Time.deltaTime.

Transform-Translate - Unity スクリプトリファレンス
translation の方向と距離に移動します

Example

I tried the following code.

Debug.Log("Before Local:" + obj.localPosition.x);
obj.Translate(-70f, 0f, 0f);
Debug.Log("After Local:" + obj.localPosition.x );

Result:

Before Local:755.3287
After Local:580.3287

The expected result for “After” was 680.3287 (750.3287 minus 70), but it was not.

PR

Why is the result different from what I expected?

Next, I tried the following code.

Debug.Log("Before Local:" + obj.localPosition.x);
Debug.Log("Before World:" + obj.position.x );
obj.Translate(-70f, 0f, 0f);
Debug.Log("After Local:" + obj.localPosition.x );
Debug.Log("After World:" + obj.position.x );

Result

Before Local:755.3287
Before World:716.1315
After Local:580.3287
After World:646.1315

As a result of the above, it can be seen that the x-coordinate in World space has been moved by -70.

This means that while the direction of Translate can be specified by the second argument and the default is the local coordinate system, the distance seems to be in the World coordinate system.

Therefore, if you try to specify the distance of movement in the local coordinate system, it will not behave as you expect.

PR

Solution

Several solutions are available, but I’ve created the following function for this purpose. (I designed it for 2D games, so the z-axis is optional.)

void MoveTransfrom(Transform obj, float x, float y, float z = 0) {
obj.localPosition = new Vector3(obj.localPosition.x + x, obj.localPosition.y + y, obj.localPosition.z + z);
}

comment

Copied title and URL