AKD
AKD

Reputation: 3966

How to copy rotation of parent object keeping self rotation as it is in unity3d

I am trying to instantiate a 3d plane game object inside a 3d plane, but the parent 3d plane's rotation could be anything, the child plane should be exact parallel to the parent 3d plane but it should keep its own rotation also.

I have tried following script, but it did not work

child.rotation = child.rotation * parent.rotation;

here I have a child plane game object names as B (rotation: -90, 0, 0) and I am making another bigger plane game object (rotation: anything) as its parent. but the child plane sometimes comes parallel to its parent plane, sometimes it doesn't when the parent plane is at some different angle/rotation.

Explanation: In below screenshot I have set child plane rotation manually in editor just by rotating 90/180 degree in required angle, the scale is automatically getting adjusted while dragging that object from world to as a child (local).

I have tried below code snippets to achieve the needful, but didn't work.

var chile = Instantiate(Resources.Load<GameObject>(prefabsPath), parent);
var t = child.transform;
t.position = pos;
t.rotation = parent.rotation;

Also I have tried

t.forward = parent.forward;

Also this one

child.SetParent(parent); // wasn't passing parent in Instantiate

above one was working perfectly in terms of scaling accordingly, but stil I wasn't able to fix rotation.

enter image description here

@derHego answer, the child plane is getting stretched like below, I experimented attaching child to different size parent planes, I found its getting stretched according to its parent scale, if parent's y is greater than x, then child's y is also getting bigger than its x with the same ratio as in parent. How do I fix this?

enter image description here

Upvotes: 2

Views: 1527

Answers (1)

derHugo
derHugo

Reputation: 90659

I assume you want both planes facing with e.g. their local Y axis in the same direction while they still might be rotated against each other around that face normal.

Depending on the direction your planes are facing you can use e.g.

child.up = parent.up;

to make both planes parallel (= pointing to the same sirection) in this case I assumed your default plane lays flad on the floor so it is facing up in Y direction


e.g.

public class Example : MonoBehaviour
{
    public Transform child;

    private void Start()
    {
        child.up = transform.up;
    }
}

enter image description here

(Green plane is parent, white plane is child)


After your update it looks like actually you could simply do

var child = Instantiate(prefab);

child.rotation = parent.rotation;

var scale = child.lossyScale;
child.SetParent(parent);

var invertParentScale = new Vector3(1 / parent.lossyScale.x, 1 / parent.lossyScale.y, 1 / parent.lossyScale.z)
child.localScale = Vector3.Scale(scale, invertParentScale);

Upvotes: 1

Related Questions