[Unity] Give an example of what pivot and anchors are and how to use them

The RectTransform component is a component used in Unity to control the position, size and rotation of UI elements. It is based on the 2D plane and is associated with the parent container of the UI element, and can realize the layout and transformation of the UI element by adjusting its properties.

Compared with the transform component, the RectTransform component is specially used to deal with the layout and transformation of UI elements, while the transform component is used to deal with the position, rotation and scaling of 3D objects. The RectTransform component provides more properties and methods to suit the special needs of UI elements.

Examples illustrate the role and usage of pivots and anchors:

1. Pivot (center point): The pivot attribute defines the center point of rotation and scaling of UI elements. It is a coordinate relative to the UI element itself, and its value ranges from (0,0) to (1,1). By default, the value of pivot is (0.5,0.5), which is the center point of the UI element. By adjusting the value of pivot, the center point of rotation and scaling of UI elements can be changed to achieve different effects.

2. Anchors (anchor): The anchors attribute defines the position and size of the UI element relative to the parent container. It is a rectangular area consisting of four boundary points (upper left, upper right, lower left, lower right). The value of anchors is the percentage position relative to the parent container, and the value range is (0,0) to (1,1). By default, the values ​​of the anchors of UI elements are (0,0) and (1,1), that is, the UI elements are aligned with the boundaries of the parent container. By adjusting the value of anchors, you can change the position and size of UI elements relative to the parent container, so as to achieve different layout effects.

For example, if you want a button to always be in the upper right corner of the parent container, you can set the anchors of the button to (1,1), which means that the upper right corner of the button is aligned with the upper right corner of the parent container. Then, you can change the center point of the button's rotation and scaling by adjusting the button's pivot property. This way the button will always be in the top right corner no matter how the size of the parent container changes.

Guess you like

Origin blog.csdn.net/andeyeluguo/article/details/131879908