跳转至专题目录
专题推荐文章:
- localPosition与anchoredPosition转化
- unity Scene View扩展之编辑器扩展总结
- Unity获取鼠标点击ui GameObject
本系列目录
- localPosition与anchoredPosition转化之瞎猫找死耗子
- localPosition与anchoredPosition转化 (✩✰✪✫✬✭✮✯★强烈推荐,个人力作!✩✰✪✫✬✭✮✯★)
- 揭秘!anchoredPosition的几何意义!
- 证·RectTransform里的localPosition就是pivot的位置
在砂糖:localPosition与anchoredPosition转化中提过,我会找个时间证明以下这个。
证明很简单,看了代码就知道用的什么方法了。
public class UILocalPosition : MonoBehaviour
{
public Transform Cube;
public Vector3 CubeLocalPosition;
public Vector3 ImageLocalPosition;
void Start()
{
}
// Update is called once per frame
void Update()
{
// 让一个Cube跟随Image的位置,然后显示Cube的localPosition,和Image的localPosition
Cube.position = transform.position;
CubeLocalPosition = Cube.localPosition;
ImageLocalPosition = transform.localPosition;
}
}
![8919f593d3424a87e43b6f839fdd82bb.png](https://i-blog.csdnimg.cn/blog_migrate/576f487c870541d7e8b50beaee06c350.png)
![f15b32d79cb743d980cef6d890788457.gif](https://i-blog.csdnimg.cn/blog_migrate/c94fb62d0e4bf89afc8e18ec4a1cb4ad.gif)
![6aca69c058a4ba8a3be7741679f46fc3.gif](https://i-blog.csdnimg.cn/blog_migrate/bd33f39f4c6876b85ae3b38cd0461d6f.gif)
// Tools.cs
internal static Vector3 GetHandlePosition()
{
Transform t = Selection.activeTransform;
if (!t)
return new Vector3(Mathf.Infinity, Mathf.Infinity, Mathf.Infinity);
Vector3 totalOffset = handleOffset + handleRotation * localHandleOffset;
switch (get.m_PivotMode)
{
case PivotMode.Center:
{
if (current == Tool.Rect)
return handleRotation * InternalEditorUtility.CalculateSelectionBoundsInSpace(Vector3.zero, handleRotation, rectBlueprintMode).center + totalOffset;
else
return InternalEditorUtility.CalculateSelectionBounds(true, false).center + totalOffset;
}
case PivotMode.Pivot:
{
if (current == Tool.Rect && rectBlueprintMode && InternalEditorUtility.SupportsRectLayout(t))
return t.parent.TransformPoint(new Vector3(t.localPosition.x, t.localPosition.y, 0)) + totalOffset;
else
return t.position + totalOffset;
}
default:
{
return new Vector3(Mathf.Infinity, Mathf.Infinity, Mathf.Infinity);
}
}
}
// RectTransformEditor
public static void SetPivotSmart(RectTransform rect, float value, int axis, bool smart, bool parentSpace)
{
Vector3 cornerBefore = GetRectReferenceCorner(rect, !parentSpace);
Vector2 rectPivot = rect.pivot;
rectPivot[axis] = value;
rect.pivot = rectPivot;
if (smart)
{
Vector3 cornerAfter = GetRectReferenceCorner(rect, !parentSpace);
Vector3 cornerOffset = cornerAfter - cornerBefore;
rect.anchoredPosition -= (Vector2)cornerOffset;
Vector3 pos = rect.transform.position;
pos.z -= cornerOffset.z;
rect.transform.position = pos;
}
}