- Home /
How can i Rotate A parent gameObject by Selecting its child gameObject?
Some Details About This Project That i am doing. I have A parent GameObject With only Transform Information and this Parent Has almost 391 Child Objects which are all rotating around the parent GameObject's Origin with a certain Offset. My Goal is that when i click on any Child GameObject, that child GameObject Will Rotate the Parent Gameobject yo the point That the this Child GameObject That Was Clicked Will face the Camera Regardless of the the current position and rotation.
Answer by DCordoba · Jan 25, 2019 at 08:47 AM
I remember something like this from the old encarta encyclopedia, when I was a child, was called visual global chooser, or something similar, well, It seem to be a simple script, was a bit, surprisingly tricky to implement, specially with handle of quaternions, they ever give me a headache
put this class on each child
public class GlobalChooser : MonoBehaviour {
public void Clicked() {
if (Input.GetMouseButtonDown (0)) {
Vector3 camPos = Camera.main.transform.position - transform.parent.position;
Quaternion rot = Quaternion.FromToRotation(transform.localPosition, camPos);
transform.parent.rotation = rot;
}
}
}
now, on a single script (we put this outside the previous script to do it only once, otherwise you will have a raycast for each child), maybe you can attach this to the parent object?
public class ClickChecker : MonoBehaviour {
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
RaycastHit Hitinfo;
if (Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition), out Hitinfo)){
GlobalChooser childScript = Hitinfo.transform.GetComponent<GlobalChooser> ();
/*this if check if what we collide is a child, every child
*must have attached a GlobalChooser script, if dont it gives null
*/
if (childScript)
childScript.Clicked();
}
}
}
}
EDIT: Please remember attach a collider to each child gameObject, to make Raycast work, it uses the colliders to detect where the mouse are pointing.
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
How do I stop objects from rotating when they collide 2 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
How to determine if rotation is clockwise or anticlockwise 2 Answers