Changing parent at runtime rotates object.
Ok, So I'm working on some 3D horror game and I want my Player to be the child of the room I'm in. Using Triggers parent are set correctly, but since the rotation of some rooms are different my Player's localRotation is changing (and Player is looking at different angle). My code fragment:
if (other.name == "corridor2")
{
if (transform.parent != corridor2.transform)
{
Debug.Log("Before (global): " + transform.eulerAngles);
Debug.Log("Before (local): " + transform.localEulerAngles);
transform.SetParent(corridor2.transform);
Debug.Log("After (global): " + transform.eulerAngles);
Debug.Log("After (local): " + transform.localEulerAngles);
}
}
Debug Results:
I've tried overriding rotation and localRotation right after parent change, but it doesn't seems to change anything.
I don't understand the problem. That is the expected behaviour. When changing the parent, the local rotation, scale and translation is changed to keep the global orientation, scale and position. In most cases that is the wanted behaviour.
If you want to keep the local values, you can use the second parameter as documented here: https://docs.unity3d.com/ScriptReference/Transform.SetParent.html
Problem is when I'm entering another room my player (with camera attached) rotates about 90 degrees (Y rotation of the room from I'm co$$anonymous$$g is 0, and room I'm going to is 270) so I'm walking straight into my trigger (function above) and then suddenly I'm walking left.
Are you using a custom player controller? If so, you should post the movement script. If not, probably some other script is accidentally using local rotation for movement.
The movement of the player is usually done using the forward axis, which is not changing when reparenting objects.
I'm using First Person Controller from Standard Assets, I don't rotate player in any of my scripts.
Debug.Log("Before (global): " + transform.eulerAngles); Debug.Log("Before (local): " + transform.localEulerAngles); Debug.Log("Before (forward): " + transform.forward); transform.SetParent(corridor2.transform); Debug.Log("After (global): " + transform.eulerAngles); Debug.Log("After (local): " + transform.localEulerAngles); Debug.Log("After (forward): " + transform.forward);
Forward axis seems not to change in any way, but my player's rotation still changes and I have no clue why. (I mean camera in game rotates, global rotation of player stays the same so it doesn't make much sense either)