- Home /
Problem turning empty object containing multiple objects
Hi
I have made a car in Unity out of various cubes and lights and put them into an empty object, so I can easily refer to the car. But my script for turning the car doesn't work as intended. Instead of just turning the car around it own axis it turns it around some point far behind it. How can I fix this, thank you in advance.
void Update () {
if(Input.GetKey(KeyCode.W)) {
transform.position += transform.forward * 5.0f * Time.deltaTime;
}
if(Input.GetKey(KeyCode.S)) {
transform.position -= transform.forward * 2.0f * Time.deltaTime;
}
if(Input.GetKey(KeyCode.A)){
transform.Rotate(0.0f, -80.0f * Time.deltaTime, 0.0f);
}
if(Input.GetKey(KeyCode.D)){
transform.Rotate(0.0f, 80.0f * Time.deltaTime, 0.0f);
}
}
Answer by ScroodgeM · Aug 26, 2012 at 05:01 PM
transform.Rotate rotates around local pivot of object, this is rather our point "behind it".
one correct way to fix this is to make pivot in car's center using 3d modelling software.
second way to avoid this is to rotate around manually calculated point
third way - create an empty GameObject X, attach car to X as child and place it so the car's center will be in X's center. rotate X instead of car
Answer by Ashkan_gc · Aug 26, 2012 at 05:15 PM
Simply when you have an empty gameObject all transformation functions (rotate and translate) work based on the position of this emply gameObject, if you place something in it's hierarchy as it's child then they should be positioned in a way that when you roate this empty object and children rotate around the parent's position, you see the correct result. so change the position of child cubes and lights and position them in a way that the empty gameObject become positioned in car center or somewhere else which your code will create correct results.
Your answer
Follow this Question
Related Questions
Car goes a bit left when moving 1 Answer
Scripting control of rotation on collision exit of terrain 2 Answers
Car Selection... 1 Answer
Rotate object horizontal with local position and localrotation 0 Answers
Turning when not seen. 0 Answers