- Home /
Combining two Quaternion rotations together
I need to rotate a Quad so that it always faces the camera and spins around it's Z axis.
I use this to rotate towards the camera. And it works fine:
transform.rotation = Quaternion.LookRotation(-whereToLook);
And I use this to spin it. And it works fine.
transform.rotation *= Quaternion.Euler(0, 0, rotationSpeed * Time.deltaTime);
But I can't make both rotations work at the same time. I've tried multiplying them in every way and nothing works as intended.
Answer by Estecka · May 20, 2017 at 03:01 PM
If you run the first line every frame, lookRotation
will constantly put the object right side up and reset its rotation around Z. The second line might make it rotate one step in the right direction, but the next frame it will be brought one step backward before being rotated again by only one step.
You could increment how much you rotate it everyframe like suggested above, but what I'd rather do is telling lookRotation
to keep the current rotation around Z instead setting the object right side up; you can do that by giving it a second parameter :
transform.rotation = Quaternion.LookRotation(-whereToLook, transform.up);
This is better/more correct. $$anonymous$$ultiply the above LookRotation by your (0, 0, RotSpeed) Quaternion and you're good to go.
Answer by Kishotta · May 20, 2017 at 02:41 PM
Try caching the local z rotation:
private Quaternion localZRotaton = Quaternion.Identity;
void Update () {
localZRotation *= Quaternion.Euler (0, 0, RotationSpeed * Time.deltaTime);
transform.rotation = Quaternion.LookRotation (-whereToLook) * localZRotation;
}
The extra multiplication is needed to repeatedly rotate around the whereToLook axis, while only applying that rotation once.
Answer by Knarhoi · Apr 25, 2020 at 07:43 PM
There's no need to use Quaternions. A simpler solution could be to use the object's forward direction. Example for a quad in 3D to always face the camera:
transform.forward = Camera.main.transform.forward;
Or in case you don't want the quad to tilt:
transform.forward = new Vector3(Camera.main.transform.forward.x, transform.forward.y, Camera.main.transform.forward.z);
You might need to invert the Z-axis, depending on your camera setup.