- Home /
Place UI objects on the top and bottom of screen object(2D sprite)
Hello! I have two panels, which is currently stretched from one edge of screen to another. If screen height is bigger than width (portrait view in smartphones), it's right, but in opposite situation height of panel dramatically grows(canvas is in "Scale with screen size" mode). I'm trying to get coordinates of my main game field sprite and convert it to screen space (no problem with that), and place panels above the max y of field and under the min y respectively. For this task I must know current size of panel sprites. But logically it size equals full screen size - _bottomPanel.rectTransform.rect.width returns full screen height. I know sprite sizes for panels and canvas reference resolution. So, currently I'm trying to place it directly behind screen, but result still depends of resolution. How can I determine UI Image screen size?
[SerializeField]
Image _bottomPanel;
[SerializeField]
Image _topPanel;
[SerializeField]
PolygonCollider2D _floor;
[SerializeField]
Camera _camera;
// Use this for initialization
void Start () {
float aspect = ((float)Screen.width / (float)Screen.height) - 1;
if(aspect > 0) {
float scaleCoef = (float)Screen.width / 1280.0f;
float scaledTopHeight = _topPanel.rectTransform.rect.height*scaleCoef;
float scaledBottomHeight = _bottomPanel.rectTransform.rect.height*scaleCoef;//trying to get ui element resolution here
float floorMaxPosition = Screen.height - _camera.WorldToScreenPoint (_floor.bounds.max).y;
float floorMinPosition = _camera.WorldToScreenPoint (_floor.bounds.min).y;
Vector3 oldBottomPosition = _bottomPanel.rectTransform.position;
Vector3 oldTopPosition = _topPanel.rectTransform.position;
_bottomPanel.rectTransform.position = new Vector3 (oldBottomPosition.x,oldBottomPosition.y - scaledBottomHeight/* + floorMinPosition*/, oldBottomPosition.z);
_topPanel.rectTransform.position = new Vector3 (oldTopPosition.x, oldTopPosition.y + scaledTopHeight/* + floorMaxPosition*/, oldTopPosition.z);
}
}
Your answer
Follow this Question
Related Questions
Make only certain UI elements block raycast/touch 3 Answers
Is making a 2d tile based game all in UI a bad solution or is it viable? 1 Answer
why is my ui being different compare to the scene after build? 0 Answers
Second camera does not show UI Image element (but does show sprite) 0 Answers
How to make a map switching system like Corpse Party Book of Shadows? 1 Answer