简体   繁体   中英

How can rotate using the mouse empty GameObject or Cube and it's childs all together?

In the Hierarchy i have a Cube i renamed it to Unit. Inside as child i have a empty GameObject renamed it as Elevator. Then as child of the Elevator i have a Cube renamed it as Platform and as child of the Platform i have another Cube renamed it to OnTop Detector.

Then as child of the Elevator i have also a Platform1(cube) and a Button(Capsule).

This is a screenshot showing it:

截图

Now what i wanted to do in general in the original is using my script to rotate the Elevator and all it's childs and childs of childs using the mouse.

If i attach the script to each and any of the childs of the Elevator i can rotate this specific object no problem. But i want to rotate them all as one unit i want to rotate the Elevator.

The problem is that on the Elevator i have Animation component with two animation clips in it. And the Animation override the rotating.

So what i tried to do is to add another Cube called it Unit and attached the script to it so i can rotate it all. The problem now is that the objects in the scene not scale as before.

I also wnat that the Unity(Cube) will not be seen and not to be collide like it's not exist if i move the player on it but i want to be able to use it to rotate all the childs objects.

This is how it looks like before i add the Unit(Cube):

Screenshot1

But once i drag the Elevator and make it child of the Unit the whole scene get messed like in the first screenshot.

This is my script:

using UnityEngine;
using System.Collections;

public class ObjectRotate : MonoBehaviour {

    public float multiplier = 10f;

    void OnMouseDrag()
    {
        transform.Rotate(Input.GetAxis("Mouse Y") * multiplier, -Input.GetAxis("Mouse X") * multiplier, 0, Space.World);
    }
}

The script is working fine to rotate each individual object but to rotate them all as one unit.

Update

After moved the Button and Platform1 to be childs of Platform they are not scaled as before like inthe first screenshot:

Screenshot2

You need to find the children of each child using a loop

void OnMouseDrag()
{
    RotateChildren(transform);
    transform.Rotate(Input.GetAxis("Mouse Y") * multiplier, -Input.GetAxis("Mouse X") * multiplier, 0, Space.World);
}

private void RotateChildren(Transform transform)
{
    foreach(Transform child in transform)
    {
        if(child.childCount > 0)
        {
            RotateChildren(child);
        }
        transform.Rotate(Input.GetAxis("Mouse Y") * multiplier, -Input.GetAxis("Mouse X") * multiplier, 0, Space.World);
    }
}

In this given example, the method calls itself if there are more children in a given child object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM