Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make child unaffected by parents rotation Unity

Tags:

c#

unity3d

I have 2 gameobjects within my character say right_obj and left_obj, I want them to ignore parent rotation, like if player change its direction (left, right), these 2 gameobjects stay on their position and rotation, so far I use 2 approaches but fail. here is my code, I use this script on my two gameobjects, but they ignour this lines

// first one approch
Quaternion rotation;
void Awake()
{
    rotation = transform.rotation;
}

void LateUpdate () 
{
    transform.rotation = rotation;
}

// 2nd approch
void LateUpdate () 
{
    transform.rotation = Quaternion.identity;;
}
like image 600
Farhan Ali Avatar asked Sep 05 '18 07:09

Farhan Ali


2 Answers

Do you really need this type of relationship?
If you don't really need the father/child relationship you can spawn an empty GameObject at 0,0,0 and spawn the actual parent and child as childs of the GameObject in the middle of the scene, this way they would still be grouped in some sort of relationship but instead of a father/child you'd get a brother/brother relationship, making the first independent from the second.

If you need to make two objects dependent from each other but not in every single way as it's supposed to be in father/child try using Parent Constraints

This way you'll obtain this type of hierarchy:
- Father GO (at 0,0,0)
-- Child1 (your actual father)
-- Child2 (your actual child)

Child1 and Child2 are syncing position by their ParentConstraint but not their rotation.

Else there is no other way than applying the opposite rotation to the child.

like image 188
Leviathan Avatar answered Nov 14 '22 06:11

Leviathan


LeviathanCode's "Parent Constraints" solution only works with Unity 2018.1+ because it's a new addition.

My suggestion isn't a "pretty" solution but it'll also work with older versions if you want to prevent imitating rotations while still copying movement:

Get rid of the parent/child relationship, add a new parent GameObject (as LeviathanCode suggested) and a script to it that simply copies the player's movement each frame:

public GameObject player; //Drag the "player" GO here in the Inspector    

public void LateUpdate() {
    transform.position = player.transform.position;
}

This way your "right_obj" and "left_obj" won't rotate like the player but still move "with" it.

like image 24
Neph Avatar answered Nov 14 '22 04:11

Neph