- Home /
How to fit a camera Viewport Rect to a UI Panel
Hello,
I'm trying to get the viewport rect of multiple cameras to fit exactly in line with some UI panels rendered on the screen. I feel like I'm close but I'm missing some offset of some sort that I just can't work out.
Here is a picture of how it's displaying currently:
And here is the code I'm using to set up the viewport rect. viewCam is the camera assigned to this "button" and parentPanelGO is the panel that contains the grid of "buttons".
void Update(){
if (parentPanelGO != null) {
Rect rekt = viewCam.rect;
Vector2 rectPos = rekt.position;
rectPos.x = Mathf.Abs (Mathf.Abs (gameObject.GetComponent<RectTransform> ().anchoredPosition.x) / Mathf.Abs (parentPanelGO.GetComponent<RectTransform> ().rect.size.x));
rectPos.y = Mathf.Abs (Mathf.Abs (gameObject.GetComponent<RectTransform> ().anchoredPosition.y) / Mathf.Abs (parentPanelGO.GetComponent<RectTransform> ().rect.size.y));
rekt.position = rectPos;
viewCam.rect = rekt;
}
}
I'm trying to calculate the viewport rect x and y by using the screen coordinates of the "button" divided by the size of the parent rect (since the viewport rect is a percentage of the screen).
Does anyone know if there is an easy way to convert a UI objects screen position to a percentage of the screen so that I can achieve this affect?
Also, is this a bad approach to this problem? Should I scrap this idea and just move the UI into world space so that I can position these screens more easily and only use 1 camera?
Thanks
Answer by AurimasBlazulionis · Dec 26, 2016 at 12:49 AM
You can always render cameras to the ender textures and then use Raw Texture component in your UI to display the cameras. Then you will only need to calculate the resolution to not have everything pixelated or have too high resolution (performance problems).
Thanks for the tip!
I'll try using a render texture and let you know how that goes
It works well, thanks!
I just need to work out the aspect ratio now.
Thanks for the quick response :)
Your answer
Follow this Question
Related Questions
Scalewithscreensize equivalent for worldspace canvas's 0 Answers
Can't position instantiated objects on canvas 2 Answers
How to make UI image in screen space look at a gameobject in world space? 0 Answers
Particle System not showing over "Screen Space - Overlay" UI Canvas 0 Answers
instantiating elements in UI/Canvas 1 Answer