- Home /
Smooth rotation to child object
I have car model which is build from different parts (separate 3d meshes such as mirrors, bumpers, wheels etc) all contained in Unity GameObject's hierarchy. The car itself stands on a cylindrical platform. Based on a part of user choice I would like it to have positioned/rotated towards the camera. For example if a mirror has been selected I would like the platform to rotate so that the mirror would become aligned with camera view. I'm attaching the code I've been working on, which of course has some errors. Help highly appreciated.
public class PlatformBase : MonoBehaviour {
private Transform selection; // selected part
private Quaternion q;
void Update ()
{
transform.rotation = Quaternion.Lerp(transform.rotation, q, Time.deltaTime);
}
public Transform Selection
{
set
{
selection = value;
angle = Vector3.Angle(
-Camera.main.transform.forward,
new Vector3(selection.forward.x, 0.0f, selection.forward.z).normalized);
q = Quaternion.AngleAxis(angle, Vector3.up);
}
That'll only work if the selected parts are not rotated in any way.
I'd just add a component to each part, with a variable on it that gives the rotation the car needs to be in to view that part. The angle you need to have to look at the mirror is very different from the angle you need to have to look at a spoiler or a wheel.
Answer by KEric · Nov 21, 2015 at 12:27 PM
The problem with the above code was in returned value of Vector3.Angle function as it returns an angle of a positive value (0, 360) whereas in the method I came up above I needed a value from (-180, 180) scope. Below I'm attaching working snipped of code
// class ...
void Update ()
{
transform.rotation = Quaternion.Lerp(transform.rotation, q, Time.deltaTime);
}
public PartUpgrade Selection
{
set
{
selection = value.transform;
Vector3 camFwd = -Camera.main.transform.forward; // camera fwd always (0, 0, -1)
Vector3 selFwd = new Vector3(selection.forward.x, 0, selection.forward.z).normalized;
angle = Vector3.Angle(camFwd, selFwd) *
Mathf.Sign(Vector3.Dot(-Vector3.up, Vector3.Cross(camFwd, selFwd)));
q = transform.rotation * Quaternion.AngleAxis(angle, Vector3.up);
}
}
Your answer
Follow this Question
Related Questions
Can anyone clearly explain what Quaternion.angleaxis is 2 Answers
How can I rotate my player with a Joystick? 0 Answers
Rotate object to target position 1 Answer
Rotate object based on hit normal + matching camera direction 0 Answers
[Unity 3D] How to detect if the game object is left right from the player? 0 Answers