【问题标题】:How to Rotate Unity UI RectTransform so that it points at another UI Element如何旋转 Unity UI RectTransform 使其指向另一个 UI 元素
【发布时间】:2017-01-06 04:17:51
【问题描述】:

如何旋转 Unity UI 元素的 RectTransform 以使该元素指向世界空间画布上的另一个 UI 元素?

在下图中,我想旋转一个滑块(但它可以是任何 UI 元素),以便当我在画布上拖动按钮时它始终面向按钮。

Example

感谢您提供的任何帮助。

【问题讨论】:

    标签: user-interface unity3d


    【解决方案1】:

    在要旋转的元素上放置一个脚本,其中包含如下内容:

    //References for the pivot position of the UI elements
    public RectTransform targetAnchor;
    RectTransform selfAnchor;
    
    //Set the rotating elements RectTransform
    void Start() {
      selfAnchor = GetComponent<RectTransform>();
    }
    
    //Update the UI elements rotation
    void Update() {
        float targetRotation = Mathf.Atan((targetAnchor.y - selfAnchor.y)/(targetAnchor.x - selfAnchor.x));
        selfAnchor.rotation = Quaternion.Euler(0,0, targetRotation);
    }
    

    我目前无法对此进行测试,但如果您仍然遇到问题,我可以在我回家时更新它。

    【讨论】:

    • ArcTan 只给出介于 -90 到 90 度之间的结果,对吗?也只是提个醒。在上面的示例中,您必须将 targetRotation 乘以 Mathf.Rad2Deg,因为 Atan 方法返回以弧度为单位的角度。
    • 除非你喜欢在你的目标和自己在同一个X坐标时被零误差除,否则强烈建议使用Mathf.Atan2而不是Mathf.Atan
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2022-11-26
    相关资源
    最近更新 更多