rotate child relative to parent,rotating child object in relation to parent
I've got a spaceship model inside a gameobject, and the engines nested in side children gameobjects.
It's designed so that you can fly directly sideways (for instance) by rotating the engines the appropriate direction.
The problem I'm having is that when the ship tilts/rotates and then fire the engine , it's correct in world space, but not in relation to the parent object.
Can you help me see I'm missing? It feels like it'll be obvious once someone points it out.
Here's the code:
void FireEngineForward()
{
FrontRightMount.transform.rotation = Quaternion.Euler(0, 0, 0);
FrontRightEngine.transform.rotation = Quaternion.Euler(0, 0, 0);
FrontLeftMount.transform.rotation = Quaternion.Euler(0, 0, 0);
FrontLeftEngine.transform.rotation = Quaternion.Euler(0, 0, 0);
BackLeftMount.transform.rotation = Quaternion.Euler(0, 0, 0);
BackLeftEngine.transform.rotation = Quaternion.Euler(0, 0, 0);
BackRightMount.transform.rotation = Quaternion.Euler(0, 0, 0);
BackRightEngine.transform.rotation = Quaternion.Euler(0, 0, 0);
}
void FireEngineBackward()
{
FrontRightMount.transform.rotation = Quaternion.Euler(0, 0, 0);
FrontRightEngine.transform.rotation = Quaternion.Euler(0, -180, 0);
FrontLeftMount.transform.rotation = Quaternion.Euler(0, 0, 0);
FrontLeftEngine.transform.rotation = Quaternion.Euler(0, -180, 0);
BackLeftMount.transform.rotation = Quaternion.Euler(0, 0, 0);
BackLeftEngine.transform.rotation = Quaternion.Euler(0, -180, 0);
BackRightMount.transform.rotation = Quaternion.Euler(0, 0, 0);
BackRightEngine.transform.rotation = Quaternion.Euler(0, -180, 0);
}
Answer by Ermiq · Mar 01, 2021 at 12:14 PM
When you attach an object to another object as a child, you shouldn't use a world rotation
as a new rotation of the child (in most cases).
Transforms have two types of`rotation` properties:
1. rotation
- represents the rotation relative to the world/scene;
2. localRotation
- represents the rotation relative to the object's parent.
When the object has no parents, its rotation
and localRotation
are the same because the object is considered to be a child of the world scene in this case. When you set an object to be a child of another object (by myObject.transform.parent = anotherObject.transform
or just dropping it on the other object in the editor hierarchy view), the child's rotation
becomes its localRotation
.
So, to properly rotate the engines to 180 degrees relative to the parent current rotation, you need to set the engines localRotation
instead of rotation
.
Answer by thetimharms · Mar 03, 2021 at 01:46 AM
A-freakin-mazing, thanks Ermiq, "localRotation" is the answer to my problem - cheers!
T