So, here’s the thing. I’m working on a top-down shooter and I’ve got some enemy prefabs. They have sliders attached to them representing their health. The camera follows the player as I move around, however, the enemy sliders don’t follow the rotation of the camera so in many cases the sliders can’t really be seen properly. I found a solution to this problem online. It’s only one line and I attached to the slider:
The transform.LookAt itself is pretty straightforward, I have no problem with that. But I can’t seem to wrap my head around the main part (transform.position + Camera.main.transform.rotation * Vector3.back).
So basically this little script works perfectly, but what exactly happens here? Why do I need to add up the transform.position and the rotation of the main camera? Then the multiplication with the Vector3.back also baffles me a bit.
I’d like to understand this so any help would be appreciated!
You need to break the operation down and learn about some linear algebra.
rotation * direction = direction
position + direction = position
Thus
position + rotation * direction = position
transform.position = position
Camera.main.transform.rotation = rotation
Vector3.back = direction
So transform.position + Camera.main.transform.rotation * Vector3.back = position is a point in space
Camera.main.transform.rotation * Vector3.back will take Vector3.back ( (0, 0, -1) ) and rotate it so it is expressed in the camera’s space. It is equivalent to the camera’s back vector
-Camera.main.transform.forward (notice the - here)
So transform.position + Camera.main.transform.rotation * Vector3.back is the position of the object minus the back vector of the camera.
My answre is based on the assumption that the line you describe is in a script which is on the gameobject of your “sliders”.
So basically what you want to achive ultimately is calculate a position in world space towards which your health bar “looks”. This can be achived in multiple ways. What your current approach does is take the Vector (0,0,-1) and it rotates it so that it is the global representation of the cameras back vector. The rotation is done by multiplying it with the cameras rotation. You should get the same result if you write -Camera.main.transform.forward.
By adding the position of your healthbar you create a point in global space in relation to your current health bar. This way you make sure that all of them are rotated the same way.
as some thoughts for further improvements of this:
if we assume you’d have a game with 1000 enemys in one area, this approach would kill the framerate on most PCs as you’d create unecessarily many calculations which all should result in the same quaternion. (This is since the direction vector you get from cameraRotation*Vector3.back is the same for all healthbars)
Here you should be able to calculate a quaternion instead: