【问题标题】:Unity - scale UI element based on closeness to a target?Unity - 基于与目标的接近程度来缩放 UI 元素?
【发布时间】:2019-03-27 20:29:47
【问题描述】:

好的,我正在使用https://bitbucket.org/beksomega/unityuiscrollsnaps/src 全向滚动,我设置了这样一个框,通过拖动将框卡到中心的紫色框:

我希望“选择”的元素或最接近目标的元素进行放大,例如 Apple 的手表应用:

在脚本中我有很多函数,比如这个:

private Vector2 FindClosestSnapPositionToPosition(Vector2 position)
        {
            EnsureLayoutHasRebuilt();

            Vector2 selected = Vector2.zero;
            float shortestDistance = Mathf.Infinity;

            foreach (Vector2 snapPosition in m_SnapPositions)
            {
                float distance = Vector2.Distance(snapPosition, position);

                if (distance < shortestDistance)
                {
                    shortestDistance = distance;
                    selected = snapPosition;
                }
            }

            return selected;
        }

并且可以打印选定的或最近的项目。如何根据与目标的接近程度进行缩放?

【问题讨论】:

    标签: c# user-interface unity3d


    【解决方案1】:

    我了解您希望在某些范围内进行缩放。假设它从比例 1 开始,并且您想要达到大小 S。我们可以定义一个距离 D,即指针和对象之间的相对距离,对象开始缩放的位置。 你可以这样做。

    /* Constants */
    const float S = 2.0f; // The maximum size you want to get when closest
    const float D = 5.0f; // The distance where you start to scale
    const float E = 1.0f; // The distance where the object will not scale more (i.e. reached the maximum)
    
    float GetIconSize(Vector2 pointer, Vector2 icon)
    {
        // Get the value between 0 and 1 from the distance between
        float factor = Mathf.InverseLerp(D, E, Vector2.Distance(pointer, icon));
    
        // Return the interpolated value size depending on the distance
        return Mathf.Lerp(1.0f, S, factor);
    }
    

    然后应用于对象(我假设它被称为“图标”)

    float size = GetIconSize(Vector2 pointer, Vector2 icon);
    icon.transform.localScale = new Vector2(size, size);
    

    您必须将指针、鼠标、手指等的位置传递给函数,第二个参数是您要缩放的图标或目标。 基本上,您需要知道两者之间的距离因子,并使用该因子在最小比例和最大比例之间进行插值。 我希望这是您想要的,如果不是,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 2021-10-09
      • 2021-01-21
      相关资源
      最近更新 更多