0
\$\begingroup\$

I am working on Context-aware camera in Unity. in this project i have to set parameters of the camera each frame manually depending on what camera sees on the screen. New View (v) direction is given and Up (u) and Right (r) vectors should be such that they minimize torsion with previous frame's u and r. I have deployed the following code to accomplish the given task:

 Vector3 viewNew = -m_Normal;      
 Vector3upNew=Vector3.Cross(viewNew,m_CameraPrevTransform.right).normalized;
 Vector3 rightNew = Vector3.Cross(viewNew, upNew).normalized;
         ...
 transform.forward = viewNew;
 transform.up = upNew;
 transform.right = rightNew;

The problem is: it seems like Unity tries to automatically adjust parameters when one of the directions (up, forward, right ) are set. Is there a workaround ? is it possible to get more control of the camera?

\$\endgroup\$
1
  • \$\begingroup\$ Here's a one-liner anyone is welcome to expand into an answer: transform.rotation = Quaternion.LookRotation(viewNew, upNew); \$\endgroup\$
    – DMGregory
    Apr 19, 2017 at 12:40

1 Answer 1

0
\$\begingroup\$

Expanding answer by @DMGregory

It takes more than one axis to specify an orientation in 3D. So when we try to set just one axis, Unity has to guess at what we want from the other axes. (Its setter can't look at the surrounding lines of code to see we're providing values for those axes too - it can only work with what it's passed) That means it might guess wrong

To avoid this, we need to combine our axis information into a complete orientation that we can set in one fell swoop. The Quaternion.LookRotation method is perfect for this: it takes up to two vectors (a desired forward and up direction, respectively) and returns a single quaternion representing the best fitting orientation, which we can assign to our transform in a single line.

Like so:

transform.rotation = Quaternion.LookRotation(viewNew, upNew);
\$\endgroup\$
3
  • \$\begingroup\$ What does it do? Why does that work? \$\endgroup\$
    – Vaillancourt
    Apr 19, 2017 at 13:11
  • 1
    \$\begingroup\$ I hope you don't mind, I've edited your answer to include a bit more explanation of why this works, now that I've got more time to write it out. Please feel free to revert or replace this with your own explanation if you prefer. \$\endgroup\$
    – DMGregory
    Apr 20, 2017 at 2:53
  • \$\begingroup\$ This is perfect. I was also researching on how to explain the difference. You did a good job. Thank you @DMGregory! \$\endgroup\$
    – Inventor
    Apr 20, 2017 at 8:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .