- Home /
UIText Inverted When Looking At Camera
I have a very simple script:
void Update()
{
if(camera == null)
{
camera = Camera.main;
}
transform.LookAt(camera.transform);
}
Its meant to make a UI element always look at the camera. I created a worldspace text, and I added this script to it.
It looks normal in the scene view before I hit play, but when I run the game, the text is inverted. It does look at the camera but its look at it with a 330* rotation which makes the text inverted!?
The only way I can get it to look normal is if I set the scale value of the x to be -x. Doing this 'fixes' the problem but Im curious why its wrong in the first place.
Do you know why my ui text is always inverted when attempting to face the camera?
Answer by Mmmpies · Feb 28, 2015 at 07:13 PM
Like a guard who's been paid not to notice a robbery you just need to look in the other direction ;¬)
transform.rotation = Quaternion.LookRotation(transform.position - camera.transform.position);
That should work but let me know if not.
First, a big thank you this DID work. Do you know why my logic was not working before? Shouldnt transform.lookat be doing this for me?
Nothing wrong with your code, the canvas's all start out at the edge of the terrain looking into the terrain I suspect this is why we always end up looking at the back of the canvas, even world space canvases, when we view it with the game camera.
To fix this we just reverse the lookat logic and effectively get the canvas to face away from it's default position.
Don't know why Unity did it this way but if you look in this tutorial:
You can see they have to manually rotate the canvas, and that's Unity tutors so it's got to be the default behavior.
I use that code to get animals to run away from the players position when they get too close to them but it works just as well with a camera and the UI.
Brilliant thanks, I had watched that tutorial but I think I missed that part. But yes very counter-intuitive. Thank you again for a very clear explanation, I was pulling my hair out haha!
Answer by lodendsg · Oct 22, 2017 at 11:47 AM
Just for note when you want a UI element to face the same direction as a given camera its better to say
transform.rotation = camera.rotation
If you set it to 'look at' the camera its going to look at the camera's pivot point and depending on your canvas distance from camera and how far from center screen the element is rendering that will be off slightly. Also its unnessisary and takes more processing than simply copying the cameras world rotation though neglagably so.
So the question is do you want your element to 'face' the camera pivot or do you want it to face toward the same direction the camera is seeing.