Things I want to do
In Unity, Transform.Translate did not translate the expected distance.
We will investigate what is happening and propose solutions.
This section discusses the amount of movement per call. For unintended behavior when repeatedly calling Update or FixedUpdate, please refer to the following (Time.deltaTime must be taken into consideration).
Specific 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 after the test was 750.3287 – 70 = 680.3287, but that’s not what happened.
Why did the results differ from what was expected?
Next, try 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 shown in the results above, the x-coordinate of the World coordinates is subtracted by 70.
In other words, the direction of the Translate function can be specified by the second argument, and the default value is the local coordinate system, but the distance is in the World coordinate system.
Therefore, attempting to specify the movement distance using the local coordinate system will not result in the expected behavior.
Solution
There are several solutions, but I created the following function. (Since it was created for 2D games, z 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);
}

コメント