- Home /
Basic quaternion question
Hi,
I am new to Unity and I am still learning how to work with quaternion...
There are 3 objects in my scene at the moment, a bear, a box, and a sphere. The bear is current looking at the box, and I want him to smoothly turn to look at the sphere.
I can make him face the sphere right away using lookAt : bear.transform.lookAt(sphere.transform);
However I would like to make him turn smoothly, so I was looking to use Quaternion.Lerp, I believe that I will need to do something like this in the void Update() : bear.transform.roation = Quaternion.Lerp(bear.transform.rotation, newQuaternion, time.deltaTime);
Now the question is, I don't know how to calculate the newQuaternion, the quaternion for him to look at the sphere.
I tried to get the bear to transform.lookAt the sphere and then copy the rotation, and then make him look at the box again, and then use Quaternion.lerp, which works but i believe this is not the right way, any suggestion?
Thank you.
Regards, Alex
Answer by danielskovli · Mar 04, 2014 at 03:53 AM
Hopefully I've understood correctly, would something like this work?
public GameObject target;
public float speed = 45f;
// Update is called once per frame
void Update () {
Vector3 direction = target.transform.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, speed * Time.deltaTime);
}
Stick that on your bear object, and drag the sphere into the target
reference. The bear will smoothly turn to look at the sphere, and keep following it forever (until you code otherwise).
Keep in mind though that this only deals with the forward-Z axis, so your bear must be modeled accordingly. I'm sure you're aware of this already though.
Cheers, Daniel
Thanks, it works. Anyway to limit it to rotate only on Y axis?
Try zeroing out the direction's Y value by adding this directly under Vector3 direction: direction.y = 0;
Your answer
Follow this Question
Related Questions
Problem finding relative rotation from one quaternion to another 4 Answers
How can I get the rotation between two objects 1 Answer
Rotate object following mouse movement. Object jumps/ flips 1 Answer
Projectile Rotation To Match Direction Shot? Mobile Joystick 2 Answers
How to make a plane face a static but rotating camera? 3 Answers