- Home /
How to pop up a world canvas close to an object and in front of the camera view?
I'm trying to pop up a world canvas close to the object selected in VR and I get an optimal result doing like this:
messageCanvas.SetActive(true);
messageCanvas.transform.position = currentSelected.position;
messageCanvas.transform.parent = currentSelected;
messageCanvas.transform.rotation = Quaternion.identity;
messageCanvas.transform.LookAt(mainCamera.transform.forward,Vector3.up);
Where messageCanvas is a gameobject containing a canvas with TextmeshPro and currentSelected is the GameObject Transform where I would like the canvas to be. I would like to have the canvas as if its forward vector was the same of my sight in order to read it better. This is the result that I have now:
What I have already tried is to use a Canvas Overlay and set is position with this function:
messageCanvas.transform.position = Camera.main.WorldToScreenPoint(selectedObject.transform.position )
but the canvas get spawned really high in the world space and I can see it only from the Scene view.
What else can I try?
Answer by FeedMyKids1 · Jun 28, 2020 at 06:43 PM
[SerializeField] GameObject messageCanvas;
[SerializeField] Transform currentSelected;
[SerializeField] float distFromSelected = 5.0f;
private void PlaceMessageCanvasAt(Transform currentSelected)
{
messageCanvas.SetActive(true);
Vector3 dirToCamera = currentSelected.position - Camera.main.transform.position;
messageCanvas.transform.position = currentSelected.position - (dirToCamera.normalized * distFromSelected);
messageCanvas.transform.LookAt(Camera.main.transform);
}
You don't have to parent the canvas to the selected object.
If the selected object is moving you would need to call this method every time it moves.
The distance from selected is how far the message canvas is from the selected object (moving toward the camera) so a bigger distance means it's closer to the camera.
You could the distance differently by adding a vector3 offset so that it's above or off to the side of your selected transform.
The only rotation you have to do is with 'LookAt'.
This works with the game camera and would not work with your scene camera.
I did a little change because the canvas was showing at the correct position, but rotated of 180 degree, so I changed the last part in messageCanvas.transform.LookAt(Camera.main.transform.forward);. Thank you from the heart
Oops. Sorry. I had tried it with a blank image so I didn't see that. Thanks for the heads up. Glad it works now.
Your answer
Follow this Question
Related Questions
How to stop collider from interfering with world space canvas? 1 Answer
World space buttons and preventing UI touch passthrough 0 Answers
3rd party UI - World Canvas or Screen Space Camera? 0 Answers
Canvas screen space to world space not working. 1 Answer
Move a 3d object from world space in the camera UI 2 Answers