예제 #1
0
    /// <summary>
    /// Activate the tweeners.
    /// </summary>

    public void Play(bool forward)
    {
        GameObject go = (tweenTarget == null) ? gameObject : tweenTarget;

        if (!NGUITools.GetActive(go))
        {
            // If the object is disabled, don't do anything
            if (ifDisabledOnPlay != EnableCondition.EnableThenPlay)
            {
                return;
            }

            // Enable the game object before tweening it
            NGUITools.SetActive(go, true);
        }

        // Gather the tweening components
        mTweens = includeChildren ? go.GetComponentsInChildren <UITweener>() : go.GetComponents <UITweener>();

        if (mTweens.Length == 0)
        {
            // No tweeners found -- should we disable the object?
            if (disableWhenFinished != DisableCondition.DoNotDisable)
            {
                NGUITools.SetActive(tweenTarget, false);
            }
        }
        else
        {
            bool activated = false;
            if (playDirection == Direction.Reverse)
            {
                forward = !forward;
            }

            // Run through all located tween components
            for (int i = 0, imax = mTweens.Length; i < imax; ++i)
            {
                UITweener tw = mTweens[i];

                // If the tweener's group matches, we can work with it
                if (tw.tweenGroup == tweenGroup)
                {
                    // Ensure that the game objects are enabled
                    if (!activated && !NGUITools.GetActive(go))
                    {
                        activated = true;
                        NGUITools.SetActive(go, true);
                    }

                    // Toggle or activate the tween component
                    if (playDirection == Direction.Toggle)
                    {
                        tw.Toggle();
                    }
                    else
                    {
                        tw.Play(forward);
                    }
                    if (resetOnPlay)
                    {
                        tw.Reset();
                    }

                    // Set the delegate
                    tw.onFinished = onFinished;

                    // Copy the event receiver
                    if (eventReceiver != null && !string.IsNullOrEmpty(callWhenFinished))
                    {
                        tw.eventReceiver    = eventReceiver;
                        tw.callWhenFinished = callWhenFinished;
                    }
                }
            }
        }
    }
예제 #2
0
    /// <summary>
    /// Display the drop-down list when the game object gets clicked on.
    /// </summary>

    void OnClick()
    {
        if (enabled && NGUITools.GetActive(gameObject) && mChild == null && atlas != null && isValid && items.Count > 0)
        {
            mLabelList.Clear();

            // Automatically locate the panel responsible for this object
            if (mPanel == null)
            {
                mPanel = UIPanel.Find(transform);
                if (mPanel == null)
                {
                    return;
                }
            }

            // Disable the navigation script
            handleEvents = true;

            // Calculate the dimensions of the object triggering the popup list so we can position it below it
            Transform myTrans = transform;
            Bounds    bounds  = NGUIMath.CalculateRelativeWidgetBounds(myTrans.parent, myTrans);

            // Create the root object for the list
            mChild       = new GameObject("Drop-down List");
            mChild.layer = gameObject.layer;

            Transform t = mChild.transform;
            t.parent        = myTrans.parent;
            t.localPosition = bounds.min;
            t.localRotation = Quaternion.identity;
            t.localScale    = Vector3.one;

            // Add a sprite for the background
            mBackground       = NGUITools.AddSprite(mChild, atlas, backgroundSprite);
            mBackground.pivot = UIWidget.Pivot.TopLeft;
            mBackground.depth = NGUITools.CalculateNextDepth(mPanel.gameObject);
            mBackground.color = backgroundColor;

            // We need to know the size of the background sprite for padding purposes
            Vector4 bgPadding = mBackground.border;
            mBgBorder = bgPadding.y;
            mBackground.cachedTransform.localPosition = new Vector3(0f, bgPadding.y, 0f);

            // Add a sprite used for the selection
            mHighlight       = NGUITools.AddSprite(mChild, atlas, highlightSprite);
            mHighlight.pivot = UIWidget.Pivot.TopLeft;
            mHighlight.color = highlightColor;

            UISpriteData hlsp = mHighlight.GetAtlasSprite();
            if (hlsp == null)
            {
                return;
            }

            float          hlspHeight = hlsp.borderTop;
            float          pixelSize = (bitmapFont != null) ? bitmapFont.pixelSize : 1f;
            float          fontHeight = activeFontSize * pixelSize;
            float          dynScale = activeFontScale;
            float          labelHeight = fontHeight * dynScale;
            float          x = 0f, y = -padding.y;
            int            labelFontSize = (bitmapFont != null) ? bitmapFont.defaultSize : fontSize;
            List <UILabel> labels        = new List <UILabel>();

            // Run through all items and create labels for each one
            for (int i = 0, imax = items.Count; i < imax; ++i)
            {
                string s = items[i];

                UILabel lbl = NGUITools.AddWidget <UILabel>(mChild);
                lbl.pivot        = UIWidget.Pivot.TopLeft;
                lbl.bitmapFont   = bitmapFont;
                lbl.trueTypeFont = trueTypeFont;
                lbl.fontSize     = labelFontSize;
                lbl.fontStyle    = fontStyle;
                lbl.text         = (isLocalized && Localization.instance != null) ? Localization.instance.Get(s) : s;
                lbl.color        = textColor;
                lbl.cachedTransform.localPosition = new Vector3(bgPadding.x + padding.x, y, -1f);
                lbl.overflowMethod = UILabel.Overflow.ResizeFreely;
                lbl.MakePixelPerfect();
                if (dynScale != 1f)
                {
                    lbl.cachedTransform.localScale = Vector3.one * dynScale;
                }
                labels.Add(lbl);

                y -= labelHeight;
                y -= padding.y;
                x  = Mathf.Max(x, lbl.printedSize.x);

                // Add an event listener
                UIEventListener listener = UIEventListener.Get(lbl.gameObject);
                listener.onHover   = OnItemHover;
                listener.onPress   = OnItemPress;
                listener.parameter = s;

                // Move the selection here if this is the right label
                if (mSelectedItem == s)
                {
                    Highlight(lbl, true);
                }

                // Add this label to the list
                mLabelList.Add(lbl);
            }

            // The triggering widget's width should be the minimum allowed width
            x = Mathf.Max(x, bounds.size.x * dynScale - (bgPadding.x + padding.x) * 2f);

            float   cx       = x / dynScale;
            Vector3 bcCenter = new Vector3(cx * 0.5f, -fontHeight * 0.5f, 0f);
            Vector3 bcSize   = new Vector3(cx, (labelHeight + padding.y) / dynScale, 1f);

            // Run through all labels and add colliders
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel     lbl = labels[i];
                BoxCollider bc  = NGUITools.AddWidgetCollider(lbl.gameObject);
                bcCenter.z = bc.center.z;
                bc.center  = bcCenter;
                bc.size    = bcSize;
            }

            x += (bgPadding.x + padding.x) * 2f;
            y -= bgPadding.y;

            // Scale the background sprite to envelop the entire set of items
            mBackground.width  = Mathf.RoundToInt(x);
            mBackground.height = Mathf.RoundToInt(-y + bgPadding.y);

            // Scale the highlight sprite to envelop a single item
            float scaleFactor = 2f * atlas.pixelSize;
            float w           = x - (bgPadding.x + padding.x) * 2f + hlsp.borderLeft * scaleFactor;
            float h           = labelHeight + hlspHeight * scaleFactor;
            mHighlight.width  = Mathf.RoundToInt(w);
            mHighlight.height = Mathf.RoundToInt(h);

            bool placeAbove = (position == Position.Above);

            if (position == Position.Auto)
            {
                UICamera cam = UICamera.FindCameraForLayer(gameObject.layer);

                if (cam != null)
                {
                    Vector3 viewPos = cam.cachedCamera.WorldToViewportPoint(myTrans.position);
                    placeAbove = (viewPos.y < 0.5f);
                }
            }

            // If the list should be animated, let's animate it by expanding it
            if (isAnimated)
            {
                float bottom = y + labelHeight;
                Animate(mHighlight, placeAbove, bottom);
                for (int i = 0, imax = labels.Count; i < imax; ++i)
                {
                    Animate(labels[i], placeAbove, bottom);
                }
                AnimateColor(mBackground);
                AnimateScale(mBackground, placeAbove, bottom);
            }

            // If we need to place the popup list above the item, we need to reposition everything by the size of the list
            if (placeAbove)
            {
                t.localPosition = new Vector3(bounds.min.x, bounds.max.y - y - bgPadding.y, bounds.min.z);
            }
        }
        else
        {
            OnSelect(false);
        }
    }
    /// <summary>
    /// Show the popup list dialog.
    /// </summary>

    public void Show()
    {
        if (enabled && NGUITools.GetActive(gameObject) && mChild == null && atlas != null && isValid && items.Count > 0)
        {
            mLabelList.Clear();

            // Automatically locate the panel responsible for this object
            if (mPanel == null)
            {
                mPanel = UIPanel.Find(transform);
                if (mPanel == null)
                {
                    return;
                }
            }

            // Disable the navigation script
            handleEvents = true;

            // Calculate the dimensions of the object triggering the popup list so we can position it below it
            Transform myTrans = transform;
            Bounds    bounds  = NGUIMath.CalculateRelativeWidgetBounds(myTrans.parent, myTrans);

            // Create the root object for the list
            mChild       = new GameObject("Drop-down List");
            mChild.layer = gameObject.layer;

            Transform t = mChild.transform;
            t.parent = myTrans.parent;
            Vector3 min;
            Vector3 max;
            Vector3 pos;

            // Manually triggered popup list on some other game object
            if (openOn == OpenOn.Manual && UICamera.selectedObject != gameObject && bounds.size == Vector3.zero)
            {
                StopCoroutine("CloseIfUnselected");
                min             = t.parent.InverseTransformPoint(mPanel.anchorCamera.ScreenToWorldPoint(UICamera.lastTouchPosition));
                max             = min;
                t.localPosition = min;
                pos             = t.position;
                StartCoroutine("CloseIfUnselected");
            }
            else
            {
                min             = bounds.min;
                max             = bounds.max;
                t.localPosition = min;
                pos             = myTrans.position;
            }

            t.localRotation = Quaternion.identity;
            t.localScale    = Vector3.one;

            // Add a sprite for the background
            mBackground       = NGUITools.AddSprite(mChild, atlas, backgroundSprite);
            mBackground.pivot = UIWidget.Pivot.TopLeft;
            mBackground.depth = NGUITools.CalculateNextDepth(mPanel.gameObject);
            mBackground.color = backgroundColor;

            // We need to know the size of the background sprite for padding purposes
            Vector4 bgPadding = mBackground.border;
            mBgBorder = bgPadding.y;
            mBackground.cachedTransform.localPosition = new Vector3(0f, bgPadding.y, 0f);

            // Add a sprite used for the selection
            mHighlight       = NGUITools.AddSprite(mChild, atlas, highlightSprite);
            mHighlight.pivot = UIWidget.Pivot.TopLeft;
            mHighlight.color = highlightColor;

            UISpriteData hlsp = mHighlight.GetAtlasSprite();
            if (hlsp == null)
            {
                return;
            }

            float          hlspHeight = hlsp.borderTop;
            float          fontHeight = activeFontSize;
            float          dynScale = activeFontScale;
            float          labelHeight = fontHeight * dynScale;
            float          x = 0f, y = -padding.y;
            List <UILabel> labels = new List <UILabel>();

            // Clear the selection if it's no longer present
            if (!items.Contains(mSelectedItem))
            {
                mSelectedItem = null;
            }

            // Run through all items and create labels for each one
            for (int i = 0, imax = items.Count; i < imax; ++i)
            {
                string s = items[i];

                UILabel lbl = NGUITools.AddWidget <UILabel>(mChild);
                lbl.name         = i.ToString();
                lbl.pivot        = UIWidget.Pivot.TopLeft;
                lbl.bitmapFont   = bitmapFont;
                lbl.trueTypeFont = trueTypeFont;
                lbl.fontSize     = fontSize;
                lbl.fontStyle    = fontStyle;
                lbl.text         = isLocalized ? Localization.Get(s) : s;
                lbl.color        = textColor;
                lbl.cachedTransform.localPosition = new Vector3(bgPadding.x + padding.x - lbl.pivotOffset.x, y, -1f);
                lbl.overflowMethod = UILabel.Overflow.ResizeFreely;
                lbl.alignment      = alignment;
                labels.Add(lbl);

                y -= labelHeight;
                y -= padding.y;
                x  = Mathf.Max(x, lbl.printedSize.x);

                // Add an event listener
                UIEventListener listener = UIEventListener.Get(lbl.gameObject);
                listener.onHover   = OnItemHover;
                listener.onPress   = OnItemPress;
                listener.onClick   = OnItemClick;
                listener.parameter = s;

                // Move the selection here if this is the right label
                if (mSelectedItem == s || (i == 0 && string.IsNullOrEmpty(mSelectedItem)))
                {
                    Highlight(lbl, true);
                }

                // Add this label to the list
                mLabelList.Add(lbl);
            }

            // The triggering widget's width should be the minimum allowed width
            x = Mathf.Max(x, bounds.size.x * dynScale - (bgPadding.x + padding.x) * 2f);

            float   cx       = x;
            Vector3 bcCenter = new Vector3(cx * 0.5f, -labelHeight * 0.5f, 0f);
            Vector3 bcSize   = new Vector3(cx, (labelHeight + padding.y), 1f);

            // Run through all labels and add colliders
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel lbl = labels[i];
                NGUITools.AddWidgetCollider(lbl.gameObject);
                lbl.autoResizeBoxCollider = false;
                BoxCollider bc = lbl.GetComponent <BoxCollider>();

                if (bc != null)
                {
                    bcCenter.z = bc.center.z;
                    bc.center  = bcCenter;
                    bc.size    = bcSize;
                }
                else
                {
                    BoxCollider2D b2d = lbl.GetComponent <BoxCollider2D>();
                    b2d.center = bcCenter;
                    b2d.size   = bcSize;
                }
            }

            int lblWidth = Mathf.RoundToInt(x);
            x += (bgPadding.x + padding.x) * 2f;
            y -= bgPadding.y;

            // Scale the background sprite to envelop the entire set of items
            mBackground.width  = Mathf.RoundToInt(x);
            mBackground.height = Mathf.RoundToInt(-y + bgPadding.y);

            // Set the label width to make alignment work
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel lbl = labels[i];
                lbl.overflowMethod = UILabel.Overflow.ShrinkContent;
                lbl.width          = lblWidth;
            }

            // Scale the highlight sprite to envelop a single item
            float scaleFactor = 2f * atlas.pixelSize;
            float w           = x - (bgPadding.x + padding.x) * 2f + hlsp.borderLeft * scaleFactor;
            float h           = labelHeight + hlspHeight * scaleFactor;
            mHighlight.width  = Mathf.RoundToInt(w);
            mHighlight.height = Mathf.RoundToInt(h);

            bool placeAbove = (position == Position.Above);

            if (position == Position.Auto)
            {
                UICamera cam = UICamera.FindCameraForLayer((UICamera.selectedObject ?? gameObject).layer);

                if (cam != null)
                {
                    Vector3 viewPos = cam.cachedCamera.WorldToViewportPoint(pos);
                    placeAbove = (viewPos.y < 0.5f);
                }
            }

            // If the list should be animated, let's animate it by expanding it
            if (isAnimated)
            {
                float bottom = y + labelHeight;
                Animate(mHighlight, placeAbove, bottom);
                for (int i = 0, imax = labels.Count; i < imax; ++i)
                {
                    Animate(labels[i], placeAbove, bottom);
                }
                AnimateColor(mBackground);
                AnimateScale(mBackground, placeAbove, bottom);
            }

            // If we need to place the popup list above the item, we need to reposition everything by the size of the list
            if (placeAbove)
            {
                t.localPosition = new Vector3(min.x, max.y - y - bgPadding.y, min.z);
            }

            min   = t.localPosition;
            max.x = min.x + mBackground.width;
            max.y = min.y + mBackground.height;
            max.z = min.z;
            Vector3 offset = mPanel.CalculateConstrainOffset(min, max);
            t.localPosition += offset;
        }
        else
        {
            OnSelect(false);
        }
    }
예제 #4
0
    /// <summary>
    /// Handles & interaction.
    /// </summary>

    public void OnSceneGUI()
    {
        if (Selection.objects.Length > 1)
        {
            return;
        }

        UICamera cam = UICamera.FindCameraForLayer(mPanel.gameObject.layer);

#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
        if (cam == null || !cam.cachedCamera.isOrthoGraphic)
        {
            return;
        }
#else
        if (cam == null || !cam.cachedCamera.orthographic)
        {
            return;
        }
#endif

        NGUIEditorTools.HideMoveTool(true);
        if (!UIWidget.showHandles)
        {
            return;
        }

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);
        Transform t    = mPanel.cachedTransform;

        Vector3[] handles = UIWidgetInspector.GetHandles(mPanel.worldCorners);

        // Time to figure out what kind of action is underneath the mouse
        UIWidgetInspector.Action actionUnderMouse = mAction;

        Color handlesColor = new Color(0.5f, 0f, 0.5f);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

        if (mPanel.isAnchored)
        {
            UIWidgetInspector.DrawAnchorHandle(mPanel.leftAnchor, mPanel.cachedTransform, handles, 0, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.topAnchor, mPanel.cachedTransform, handles, 1, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.rightAnchor, mPanel.cachedTransform, handles, 2, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.bottomAnchor, mPanel.cachedTransform, handles, 3, id);
        }

        if (type == EventType.Repaint)
        {
            bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
            if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control)
            {
                showDetails = true;
            }
            if (NGUITools.GetActive(mPanel) && mPanel.parent == null)
            {
                showDetails = true;
            }
            if (showDetails)
            {
                NGUIHandles.DrawSize(handles, Mathf.RoundToInt(mPanel.width), Mathf.RoundToInt(mPanel.height));
            }
        }

        bool canResize = (mPanel.clipping != UIDrawCall.Clipping.None);

        // NOTE: Remove this part when it's possible to neatly resize rotated anchored panels.
        if (canResize && mPanel.isAnchored)
        {
            Quaternion rot = mPanel.cachedTransform.localRotation;
            if (Quaternion.Angle(rot, Quaternion.identity) > 0.01f)
            {
                canResize = false;
            }
        }

        bool[] resizable = new bool[8];

        resizable[4] = canResize;                    // left
        resizable[5] = canResize;                    // top
        resizable[6] = canResize;                    // right
        resizable[7] = canResize;                    // bottom

        resizable[0] = resizable[7] && resizable[4]; // bottom-left
        resizable[1] = resizable[5] && resizable[4]; // top-left
        resizable[2] = resizable[5] && resizable[6]; // top-right
        resizable[3] = resizable[7] && resizable[6]; // bottom-right

        UIWidget.Pivot pivotUnderMouse = UIWidgetInspector.GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);

        switch (type)
        {
        case EventType.Repaint:
        {
            Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
            Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

            if ((v2 - v0).magnitude > 60f)
            {
                Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                Handles.BeginGUI();
                {
                    for (int i = 0; i < 4; ++i)
                    {
                        DrawKnob(handles[i], id, resizable[i]);
                    }

                    if (Mathf.Abs(v1.y - v0.y) > 80f)
                    {
                        if (mPanel.leftAnchor.target == null || mPanel.leftAnchor.absolute != 0)
                        {
                            DrawKnob(handles[4], id, resizable[4]);
                        }

                        if (mPanel.rightAnchor.target == null || mPanel.rightAnchor.absolute != 0)
                        {
                            DrawKnob(handles[6], id, resizable[6]);
                        }
                    }

                    if (Mathf.Abs(v3.x - v0.x) > 80f)
                    {
                        if (mPanel.topAnchor.target == null || mPanel.topAnchor.absolute != 0)
                        {
                            DrawKnob(handles[5], id, resizable[5]);
                        }

                        if (mPanel.bottomAnchor.target == null || mPanel.bottomAnchor.absolute != 0)
                        {
                            DrawKnob(handles[7], id, resizable[7]);
                        }
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            if (actionUnderMouse != UIWidgetInspector.Action.None)
            {
                mStartMouse     = e.mousePosition;
                mAllowSelection = true;

                if (e.button == 1)
                {
                    if (e.modifiers == 0)
                    {
                        GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                        e.Use();
                    }
                }
                else if (e.button == 0 && actionUnderMouse != UIWidgetInspector.Action.None &&
                         UIWidgetInspector.Raycast(handles, out mStartDrag))
                {
                    mWorldPos             = t.position;
                    mLocalPos             = t.localPosition;
                    mStartRot             = t.localRotation.eulerAngles;
                    mStartDir             = mStartDrag - t.position;
                    mStartCR              = mPanel.baseClipRegion;
                    mDragPivot            = pivotUnderMouse;
                    mActionUnderMouse     = actionUnderMouse;
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Open a context menu listing all widgets underneath
                        NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                        handled = true;
                    }
                    else if (mAction == UIWidgetInspector.Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the topmost widget
                            NGUIEditorTools.SelectWidget(e.mousePosition);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                        handled         = true;
                    }

                    if (handled)
                    {
                        e.Use();
                    }
                }

                // Clear the actions
                mActionUnderMouse = UIWidgetInspector.Action.None;
                mAction           = UIWidgetInspector.Action.None;
            }
            else if (mAllowSelection)
            {
                List <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.Count > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != UIWidgetInspector.Action.None || mActionUnderMouse != UIWidgetInspector.Action.None)
                {
                    Vector3 pos;

                    if (UIWidgetInspector.Raycast(handles, out pos))
                    {
                        if (mAction == UIWidgetInspector.Action.None && mActionUnderMouse != UIWidgetInspector.Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == UIWidgetInspector.Action.Move)
                                {
                                    NGUISnap.Recalculate(mPanel);
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Scale)
                                {
                                    mStartCR   = mPanel.baseClipRegion;
                                    mDragPivot = pivotUnderMouse;
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != UIWidgetInspector.Action.None)
                        {
                            NGUIEditorTools.RegisterUndo("Change Rect", t);
                            NGUIEditorTools.RegisterUndo("Change Rect", mPanel);

                            if (mAction == UIWidgetInspector.Action.Move)
                            {
                                Vector3 before      = t.position;
                                Vector3 beforeLocal = t.localPosition;
                                t.position = mWorldPos + (pos - mStartDrag);
                                pos        = NGUISnap.Snap(t.localPosition, mPanel.localCorners,
                                                           e.modifiers != EventModifiers.Control) - beforeLocal;
                                t.position = before;

                                NGUIMath.MoveRect(mPanel, pos.x, pos.y);
                            }
                            else if (mAction == UIWidgetInspector.Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
                                            Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == UIWidgetInspector.Action.Scale)
                            {
                                // World-space delta since the drag started
                                Vector3 delta = pos - mStartDrag;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                AdjustClipping(mPanel, mLocalPos, mStartCR, delta, mDragPivot);
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, 1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, -1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, -1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != UIWidgetInspector.Action.None)
                    {
                        Undo.PerformUndo();
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = UIWidgetInspector.Action.None;
                    mAction           = UIWidgetInspector.Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
예제 #5
0
    /// <summary>
    /// This callback is sent inside the editor notifying us that some property has changed.
    /// </summary>

    protected override void OnValidate()
    {
        if (NGUITools.GetActive(this))
        {
            base.OnValidate();

            // Prior to NGUI 2.7.0 width and height was specified as transform's local scale
            if ((mWidth == 100 || mWidth == minWidth) &&
                (mHeight == 100 || mHeight == minHeight) && cachedTransform.localScale.magnitude > 8f)
            {
                UpgradeFrom265();
                cachedTransform.localScale = Vector3.one;
            }

            if (mWidth < minWidth)
            {
                mWidth = minWidth;
            }
            if (mHeight < minHeight)
            {
                mHeight = minHeight;
            }
            if (autoResizeBoxCollider)
            {
                ResizeCollider();
            }

            // If the texture is changing, we need to make sure to rebuild the draw calls
            if (mOldTex != mainTexture || mOldShader != shader)
            {
                mOldTex    = mainTexture;
                mOldShader = shader;
            }

            if (panel != null)
            {
                panel.RemoveWidget(this);
                panel = null;
            }

            aspectRatio = (keepAspectRatio == AspectRatioSource.Free) ?
                          (float)mWidth / mHeight : Mathf.Max(0.01f, aspectRatio);

            if (keepAspectRatio == AspectRatioSource.BasedOnHeight)
            {
                mWidth = Mathf.RoundToInt(mHeight * aspectRatio);
            }
            else if (keepAspectRatio == AspectRatioSource.BasedOnWidth)
            {
                mHeight = Mathf.RoundToInt(mWidth / aspectRatio);
            }
            CreatePanel();
        }
        else
        {
            if (mWidth < minWidth)
            {
                mWidth = minWidth;
            }
            if (mHeight < minHeight)
            {
                mHeight = minHeight;
            }
        }
    }
예제 #6
0
    /// <summary>
    /// Recalculate the position of all elements within the grid, sorting them alphabetically if necessary.
    /// </summary>

    public void Reposition()
    {
        if (!mStarted)
        {
            repositionNow = true;
            return;
        }

        Transform myTrans = transform;

        int x = 0;
        int y = 0;

        if (sorted)
        {
            List <Transform> list = new List <Transform>();

            for (int i = 0; i < myTrans.childCount; ++i)
            {
                Transform t = myTrans.GetChild(i);
                if (t && (!hideInactive || NGUITools.GetActive(t.gameObject)))
                {
                    list.Add(t);
                }
            }
            list.Sort(SortByName);

            for (int i = 0, imax = list.Count; i < imax; ++i)
            {
                Transform t = list[i];

                if (!NGUITools.GetActive(t.gameObject) && hideInactive)
                {
                    continue;
                }

                float depth = t.localPosition.z;
                t.localPosition = (arrangement == Arrangement.Horizontal) ?
                                  new Vector3(cellWidth * x, -cellHeight * y, depth) :
                                  new Vector3(cellWidth * y, -cellHeight * x, depth);

                if (++x >= maxPerLine && maxPerLine > 0)
                {
                    x = 0;
                    ++y;
                }
            }
        }
        else
        {
            for (int i = 0; i < myTrans.childCount; ++i)
            {
                Transform t = myTrans.GetChild(i);

                if (!NGUITools.GetActive(t.gameObject) && hideInactive)
                {
                    continue;
                }

                float depth = t.localPosition.z;
                t.localPosition = (arrangement == Arrangement.Horizontal) ?
                                  new Vector3(cellWidth * x, -cellHeight * y, depth) :
                                  new Vector3(cellWidth * y, -cellHeight * x, depth);

                if (++x >= maxPerLine && maxPerLine > 0)
                {
                    x = 0;
                    ++y;
                }
            }
        }

        UIDraggablePanel drag = NGUITools.FindInParents <UIDraggablePanel>(gameObject);

        if (drag != null)
        {
            drag.UpdateScrollbars(true);
        }
    }
예제 #7
0
    /// <summary>
    /// Draw the on-screen selection, knobs, and handle all interaction logic.
    /// </summary>

    public void OnSceneGUI()
    {
        if (Selection.objects.Length > 1)
        {
            return;
        }
        NGUIEditorTools.HideMoveTool(true);
        if (!UIWidget.showHandles)
        {
            return;
        }

        mWidget = target as UIWidget;

        Transform t = mWidget.cachedTransform;

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);

        Action actionUnderMouse = mAction;

        Vector3[] handles = GetHandles(mWidget.worldCorners);

        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

        // If the widget is anchored, draw the anchors
        if (mWidget.isAnchored)
        {
            DrawAnchorHandle(mWidget.leftAnchor, mWidget.cachedTransform, handles, 0, id);
            DrawAnchorHandle(mWidget.topAnchor, mWidget.cachedTransform, handles, 1, id);
            DrawAnchorHandle(mWidget.rightAnchor, mWidget.cachedTransform, handles, 2, id);
            DrawAnchorHandle(mWidget.bottomAnchor, mWidget.cachedTransform, handles, 3, id);
        }

        if (type == EventType.Repaint)
        {
            bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
            if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control)
            {
                showDetails = true;
            }
            if (NGUITools.GetActive(mWidget) && mWidget.parent == null)
            {
                showDetails = true;
            }
            if (showDetails)
            {
                NGUIHandles.DrawSize(handles, mWidget.width, mWidget.height);
            }
        }

        // Presence of the legacy stretch component prevents resizing
        bool canResize = (mWidget.GetComponent <UIStretch>() == null);

        bool[] resizable = new bool[8];

        resizable[4] = canResize;               // left
        resizable[5] = canResize;               // top
        resizable[6] = canResize;               // right
        resizable[7] = canResize;               // bottom

        UILabel lbl = mWidget as UILabel;

        if (lbl != null)
        {
            if (lbl.overflowMethod == UILabel.Overflow.ResizeFreely)
            {
                resizable[4] = false;                   // left
                resizable[5] = false;                   // top
                resizable[6] = false;                   // right
                resizable[7] = false;                   // bottom
            }
            else if (lbl.overflowMethod == UILabel.Overflow.ResizeHeight)
            {
                resizable[5] = false;                   // top
                resizable[7] = false;                   // bottom
            }
        }

        if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnHeight)
        {
            resizable[4] = false;
            resizable[6] = false;
        }
        else if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnWidth)
        {
            resizable[5] = false;
            resizable[7] = false;
        }

        resizable[0] = resizable[7] && resizable[4];         // bottom-left
        resizable[1] = resizable[5] && resizable[4];         // top-left
        resizable[2] = resizable[5] && resizable[6];         // top-right
        resizable[3] = resizable[7] && resizable[6];         // bottom-right

        UIWidget.Pivot pivotUnderMouse = GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);

        switch (type)
        {
        case EventType.Repaint:
        {
            Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
            Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

            if ((v2 - v0).magnitude > 60f)
            {
                Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                Handles.BeginGUI();
                {
                    for (int i = 0; i < 4; ++i)
                    {
                        DrawKnob(handles[i], mWidget.pivot == pivotPoints[i], resizable[i], id);
                    }

                    if ((v1 - v0).magnitude > 80f)
                    {
                        if (mWidget.leftAnchor.target == null || mWidget.leftAnchor.absolute != 0)
                        {
                            DrawKnob(handles[4], mWidget.pivot == pivotPoints[4], resizable[4], id);
                        }

                        if (mWidget.rightAnchor.target == null || mWidget.rightAnchor.absolute != 0)
                        {
                            DrawKnob(handles[6], mWidget.pivot == pivotPoints[6], resizable[6], id);
                        }
                    }

                    if ((v3 - v0).magnitude > 80f)
                    {
                        if (mWidget.topAnchor.target == null || mWidget.topAnchor.absolute != 0)
                        {
                            DrawKnob(handles[5], mWidget.pivot == pivotPoints[5], resizable[5], id);
                        }

                        if (mWidget.bottomAnchor.target == null || mWidget.bottomAnchor.absolute != 0)
                        {
                            DrawKnob(handles[7], mWidget.pivot == pivotPoints[7], resizable[7], id);
                        }
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            if (actionUnderMouse != Action.None)
            {
                mStartMouse     = e.mousePosition;
                mAllowSelection = true;

                if (e.button == 1)
                {
                    if (e.modifiers == 0)
                    {
                        GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                        e.Use();
                    }
                }
                else if (e.button == 0 && actionUnderMouse != Action.None && Raycast(handles, out mStartDrag))
                {
                    mWorldPos      = t.position;
                    mLocalPos      = t.localPosition;
                    mStartRot      = t.localRotation.eulerAngles;
                    mStartDir      = mStartDrag - t.position;
                    mStartWidth    = mWidget.width;
                    mStartHeight   = mWidget.height;
                    mStartLeft.x   = mWidget.leftAnchor.relative;
                    mStartLeft.y   = mWidget.leftAnchor.absolute;
                    mStartRight.x  = mWidget.rightAnchor.relative;
                    mStartRight.y  = mWidget.rightAnchor.absolute;
                    mStartBottom.x = mWidget.bottomAnchor.relative;
                    mStartBottom.y = mWidget.bottomAnchor.absolute;
                    mStartTop.x    = mWidget.topAnchor.relative;
                    mStartTop.y    = mWidget.topAnchor.absolute;

                    mDragPivot            = pivotUnderMouse;
                    mActionUnderMouse     = actionUnderMouse;
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != Action.None || mActionUnderMouse != Action.None)
                {
                    Vector3 pos;

                    if (Raycast(handles, out pos))
                    {
                        if (mAction == Action.None && mActionUnderMouse != Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == Action.Move)
                                {
                                    NGUISnap.Recalculate(mWidget);
                                }
                                else if (mActionUnderMouse == Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                }
                                else if (mActionUnderMouse == Action.Scale)
                                {
                                    mStartWidth  = mWidget.width;
                                    mStartHeight = mWidget.height;
                                    mDragPivot   = pivotUnderMouse;
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != Action.None)
                        {
                            NGUIEditorTools.RegisterUndo("Change Rect", t);
                            NGUIEditorTools.RegisterUndo("Change Rect", mWidget);

                            // Reset the widget before adjusting anything
                            t.position     = mWorldPos;
                            mWidget.width  = mStartWidth;
                            mWidget.height = mStartHeight;
                            mWidget.leftAnchor.Set(mStartLeft.x, mStartLeft.y);
                            mWidget.rightAnchor.Set(mStartRight.x, mStartRight.y);
                            mWidget.bottomAnchor.Set(mStartBottom.x, mStartBottom.y);
                            mWidget.topAnchor.Set(mStartTop.x, mStartTop.y);

                            if (mAction == Action.Move)
                            {
                                // Move the widget
                                t.position = mWorldPos + (pos - mStartDrag);
                                Vector3 after = t.localPosition;

                                bool      snapped = false;
                                Transform parent  = t.parent;

                                if (parent != null)
                                {
                                    UIGrid grid = parent.GetComponent <UIGrid>();

                                    if (grid != null && grid.arrangement == UIGrid.Arrangement.CellSnap)
                                    {
                                        snapped = true;
                                        if (grid.cellWidth > 0)
                                        {
                                            after.x = Mathf.Round(after.x / grid.cellWidth) * grid.cellWidth;
                                        }
                                        if (grid.cellHeight > 0)
                                        {
                                            after.y = Mathf.Round(after.y / grid.cellHeight) * grid.cellHeight;
                                        }
                                    }
                                }

                                if (!snapped)
                                {
                                    // Snap the widget
                                    after = NGUISnap.Snap(after, mWidget.localCorners, e.modifiers != EventModifiers.Control);
                                }

                                // Calculate the final delta
                                Vector3 localDelta = (after - mLocalPos);

                                // Restore the position
                                t.position = mWorldPos;

                                // Adjust the widget by the delta
                                NGUIMath.MoveRect(mWidget, localDelta.x, localDelta.y);
                            }
                            else if (mAction == Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
                                            Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == Action.Scale)
                            {
                                // Move the widget
                                t.position = mWorldPos + (pos - mStartDrag);

                                // Calculate the final delta
                                Vector3 localDelta = (t.localPosition - mLocalPos);

                                // Restore the position
                                t.position = mWorldPos;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                NGUIMath.ResizeWidget(mWidget, mDragPivot, localDelta.x, localDelta.y, 2, 2);
                                ReEvaluateAnchorType();
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (e.button == 2)
            {
                break;
            }
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Open a context menu listing all widgets underneath
                        NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                        handled = true;
                    }
                    else if (mAction == Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the topmost widget
                            NGUIEditorTools.SelectWidget(e.mousePosition);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                        handled         = true;
                    }

                    if (handled)
                    {
                        e.Use();
                    }
                }

                // Clear the actions
                mActionUnderMouse = Action.None;
                mAction           = Action.None;
            }
            else if (mAllowSelection)
            {
                List <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.Count > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 0f, 1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 0f, -1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, -1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != Action.None)
                    {
                        Undo.PerformUndo();
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = Action.None;
                    mAction           = Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
예제 #8
0
    public virtual void Reposition()
    {
        if (Application.isPlaying && !mInitDone && NGUITools.GetActive(this))
        {
            mReposition = true;
            return;
        }

        if (!mInitDone)
        {
            Init();
        }

        mReposition = false;
        Transform myTrans = transform;

        int x    = 0;
        int y    = 0;
        int maxX = 0;
        int maxY = 0;

        if (sorting != Sorting.None || sorted)
        {
            BetterList <Transform> list = new BetterList <Transform>();

            for (int i = 0; i < myTrans.childCount; ++i)
            {
                Transform t = myTrans.GetChild(i);
                if (t && (!hideInactive || NGUITools.GetActive(t.gameObject)))
                {
                    list.Add(t);
                }
            }

            if (sorting == Sorting.Alphabetic)
            {
                list.Sort(SortByName);
            }
            else if (sorting == Sorting.Horizontal)
            {
                list.Sort(SortHorizontal);
            }
            else if (sorting == Sorting.Vertical)
            {
                list.Sort(SortVertical);
            }
            else
            {
                Sort(list);
            }

            for (int i = 0, imax = list.size; i < imax; ++i)
            {
                Transform t = list[i];

                if (!NGUITools.GetActive(t.gameObject) && hideInactive)
                {
                    continue;
                }

                float   depth = t.localPosition.z;
                Vector3 pos   = (arrangement == Arrangement.Horizontal) ?
                                new Vector3(cellWidth * x, -cellHeight * y, depth) :
                                new Vector3(cellWidth * y, -cellHeight * x, depth);

                if (animateSmoothly && Application.isPlaying)
                {
                    SpringPosition.Begin(t.gameObject, pos, 15f).updateScrollView = true;
                }
                else
                {
                    t.localPosition = pos;
                }

                maxX = Mathf.Max(maxX, x);
                maxY = Mathf.Max(maxY, y);

                if (++x >= maxPerLine && maxPerLine > 0)
                {
                    x = 0;
                    ++y;
                }
            }
        }
        else
        {
            for (int i = 0; i < myTrans.childCount; ++i)
            {
                Transform t = myTrans.GetChild(i);

                if (!NGUITools.GetActive(t.gameObject) && hideInactive)
                {
                    continue;
                }

                float   depth = t.localPosition.z;
                Vector3 pos   = (arrangement == Arrangement.Horizontal) ?
                                new Vector3(cellWidth * x, -cellHeight * y, depth) :
                                new Vector3(cellWidth * y, -cellHeight * x, depth);

                if (animateSmoothly && Application.isPlaying)
                {
                    SpringPosition.Begin(t.gameObject, pos, 15f).updateScrollView = true;
                }
                else
                {
                    t.localPosition = pos;
                }

                maxX = Mathf.Max(maxX, x);
                maxY = Mathf.Max(maxY, y);

                if (++x >= maxPerLine && maxPerLine > 0)
                {
                    x = 0;
                    ++y;
                }
            }
        }

        // Apply the origin offset
        if (pivot != UIWidget.Pivot.TopLeft)
        {
            Vector2 po = NGUIMath.GetPivotOffset(pivot);

            float fx, fy;

            if (arrangement == Arrangement.Horizontal)
            {
                fx = Mathf.Lerp(0f, maxX * cellWidth, po.x);
                fy = Mathf.Lerp(-maxY * cellHeight, 0f, po.y);
            }
            else
            {
                fx = Mathf.Lerp(0f, maxY * cellWidth, po.x);
                fy = Mathf.Lerp(-maxX * cellHeight, 0f, po.y);
            }

            for (int i = 0; i < myTrans.childCount; ++i)
            {
                Transform t = myTrans.GetChild(i);

                if (!NGUITools.GetActive(t.gameObject) && hideInactive)
                {
                    continue;
                }

                SpringPosition sp = t.GetComponent <SpringPosition>();

                if (sp != null)
                {
                    sp.target.x -= fx;
                    sp.target.y -= fy;
                }
                else
                {
                    Vector3 pos = t.localPosition;
                    pos.x          -= fx;
                    pos.y          -= fy;
                    t.localPosition = pos;
                }
            }
        }

        if (keepWithinPanel && mPanel != null)
        {
            mPanel.ConstrainTargetToBounds(myTrans, true);
        }

        if (onReposition != null)
        {
            onReposition();
        }
    }
예제 #9
0
    public void PerFrameUpdate()
    {
        //run delay timer for tooltip
        if (_isShowingToolTip)
        {
            if (!NGUITools.GetActive(ToolTip))
            {
                NGUITools.SetActive(ToolTip.gameObject, true);
            }

            Vector3 pos = Input.mousePosition + new Vector3(0, 10, 0);
            pos.x = Mathf.Clamp01(pos.x / Screen.width);
            pos.y = Mathf.Clamp01(pos.y / Screen.height);
            ToolTip.transform.position = GameManager.Inst.UIManager.UICamera.ViewportToWorldPoint(pos);;
            //_toolTipTimer = 0;

            /*
             * if(_toolTipTimer < ToolTipDelay)
             * {
             *      _toolTipTimer += Time.unscaledDeltaTime;
             * }
             * else
             * {
             *
             * }
             */
        }

        if (InputEventHandler.Instance.State == UserInputState.PopupOpen || InputEventHandler.Instance.State == UserInputState.Dialogue)
        {
            SetCursorState(CursorState.Default);
            HideToolTip();
            GameManager.Inst.UIManager.HUDPanel.HideTargetName();
        }

        //Debug.Log(Input.mousePosition);
        if (GameManager.Inst.PlayerControl.IsGamePaused || InputEventHandler.Instance.State != UserInputState.Normal)
        {
            return;
        }

        //UnityEngine.Cursor.visible = false;
        if (CurrentState == CursorState.Aim)
        {
            UnityEngine.Cursor.visible = false;

            AimCursor aimCursor = ActiveCursor.GetComponent <AimCursor>();
            if (aimCursor != null)
            {
                //float climb = GameManager.Inst.PlayerControl.SelectedPC.AimTarget.localPosition.y;
                float armFatigue = GameManager.Inst.PlayerControl.SelectedPC.MyStatus.ArmFatigue / GameManager.Inst.PlayerControl.SelectedPC.MyStatus.MaxArmFatigue;
                float amount     = GameManager.Inst.Constants.ArmFatigueRecoil.Evaluate(Mathf.Clamp(armFatigue, 0, 1));
                float baseAmount = 5;
                if (GameManager.Inst.PlayerControl.SelectedPC.IsHipAiming || GameManager.Inst.PlayerControl.SelectedPC.UpperBodyState != HumanUpperBodyStates.Aim)
                {
                    baseAmount = 15;
                }
                amount = amount * 100 + baseAmount + 20 * GameManager.Inst.PlayerControl.SelectedPC.MyAI.WeaponSystem.GetTurnMoveScatter();
                aimCursor.SetExpansion(amount);

                Weapon currentWeapon = GameManager.Inst.PlayerControl.SelectedPC.MyReference.CurrentWeapon.GetComponent <Weapon>();
                if (currentWeapon.IsRanged)
                {
                    Gun gun = (Gun)currentWeapon;
                    if (gun.Barrel.Range < Vector3.Distance(GameManager.Inst.PlayerControl.SelectedPC.transform.position, GameManager.Inst.PlayerControl.SelectedPC.AimPoint))
                    {
                        SetCrosshairState(aimCursor, true);
                    }
                    else
                    {
                        SetCrosshairState(aimCursor, false);
                    }
                }
                else
                {
                    SetCrosshairState(aimCursor, false);
                }
            }
        }
        else
        {
            UnityEngine.Cursor.visible = true;
        }


        float centerAlpha = CursorAim.GetComponent <AimCursor>().AimCursorCenter.alpha;

        CursorAim.GetComponent <AimCursor>().SetCenterCursorAlpha(Mathf.Lerp(centerAlpha, 0, Time.deltaTime * 3));
        //update cursor state based on what player is doing

        GameObject aimedObject = GameManager.Inst.PlayerControl.GetAimedObject();


        if (GameManager.Inst.PlayerControl.SelectedPC.MyAI.ControlType == AIControlType.Player)
        {
            //if(GameManager.Inst.PlayerControl.SelectedPC.GetCurrentAnimWeapon() != WeaponAnimType.Unarmed && !GameManager.Inst.UIManager.IsCursorInHUDRegion())
            if ((GameManager.Inst.PlayerControl.SelectedPC.UpperBodyState == HumanUpperBodyStates.Aim ||
                 GameManager.Inst.PlayerControl.SelectedPC.UpperBodyState == HumanUpperBodyStates.HalfAim) &&
                !GameManager.Inst.UIManager.IsCursorInHUDRegion())
            {
                SetCursorState(CursorState.Aim);

                /*
                 * //now check if aimed object is enemy
                 * Character aimedChar = GameManager.Inst.PlayerControl.GetAimedObject().GetComponent<Character>();
                 * if(aimedChar != null && aimedChar.Faction != GameManager.Inst.PlayerControl.SelectedPC.Faction)
                 * {
                 *      //mark cursor as red
                 *      CursorAim.color = new Color(1, 0, 0);
                 * }
                 */
            }
            else if (aimedObject != null && Vector3.Distance(GameManager.Inst.PlayerControl.SelectedPC.transform.position, aimedObject.transform.position) < 15)
            {
                if (aimedObject.GetComponent <PickupItem>() != null)
                {
                    PickupItem pickup   = aimedObject.GetComponent <PickupItem>();
                    string     quantity = "";
                    if (pickup.Quantity > 1)
                    {
                        quantity = "(" + pickup.Quantity + ")";
                    }
                    //ShowToolTip(pickup.Item.Name + quantity);
                    GameManager.Inst.UIManager.HUDPanel.ShowTargetName(pickup.Item.Name + quantity, 1);
                    SetCursorState(CursorState.Hand);
                }
                else if (aimedObject.GetComponent <StoryObject>() != null)
                {
                    //ShowToolTip(aimedObject.GetComponent<StoryObject>().Name);
                    GameManager.Inst.UIManager.HUDPanel.ShowTargetName(aimedObject.GetComponent <StoryObject>().Name, 1);
                    SetCursorState(CursorState.Hand);
                }
                else if (aimedObject.GetComponent <Character>() != null)
                {
                    Character aimedCharacter = aimedObject.GetComponent <Character>();
                    int       relationship   = aimedCharacter.MyAI.IsCharacterEnemy((Character)GameManager.Inst.PlayerControl.SelectedPC);
                    if (aimedCharacter != null && aimedCharacter.MyStatus.Health > 0 && relationship >= 2 &&
                        aimedCharacter.MyAI.ControlType != AIControlType.Player && !aimedCharacter.IsHidden)
                    {
                        SetCursorState(CursorState.Talk);
                    }
                    else
                    {
                        SetCursorState(CursorState.Default);
                    }

                    string name = aimedCharacter.Name;
                    if (relationship < 1)
                    {
                        name = aimedCharacter.Faction.ToString();
                    }
                    if (!string.IsNullOrEmpty(aimedCharacter.Title))
                    {
                        name = aimedCharacter.Title + " " + name;
                    }

                    if (!string.IsNullOrEmpty(name) && !aimedCharacter.IsHidden)
                    {
                        //ShowToolTip(name);
                        GameManager.Inst.UIManager.HUDPanel.ShowTargetName(name, relationship);
                    }
                }
                else if (aimedObject.tag == "SerumLab")
                {
                    //ShowToolTip("Serum Lab");
                    GameManager.Inst.UIManager.HUDPanel.ShowTargetName("Serum Lab", 1);
                    SetCursorState(CursorState.Hand);
                }
                else
                {
                    DeathCollider deathCollider = aimedObject.GetComponent <DeathCollider>();
                    if (deathCollider != null)
                    {
                        Character aimedCharacter = deathCollider.ParentCharacter;
                        if (aimedCharacter != null && aimedCharacter.MyStatus.Health <= 0)
                        {
                            SetCursorState(CursorState.Hand);
                        }
                        else
                        {
                            SetCursorState(CursorState.Default);
                        }
                    }
                    else if (aimedObject.tag == "Chest" && aimedObject.GetComponent <Chest>() != null)
                    {
                        SetCursorState(CursorState.Hand);
                    }
                    else if (aimedObject.tag == "Door" || aimedObject.tag == "LightSwitch")
                    {
                        SetCursorState(CursorState.Hand);
                    }
                    else if (aimedObject.tag == "Portal")
                    {
                        SetCursorState(CursorState.Portal);
                    }
                    else
                    {
                        //Debug.Log("setting cursor to default");
                        SetCursorState(CursorState.Default);
                    }

                    HideToolTip();
                    GameManager.Inst.UIManager.HUDPanel.FadeTargetName();
                }
            }
            else
            {
                //Debug.Log("setting cursor to default");
                SetCursorState(CursorState.Default);
                HideToolTip();
                GameManager.Inst.UIManager.HUDPanel.FadeTargetName();
            }
        }
        else
        {
            //Debug.Log("setting cursor to default");
            SetCursorState(CursorState.Default);
            HideToolTip();
            GameManager.Inst.UIManager.HUDPanel.HideTargetName();
        }
    }
예제 #10
0
 public void Show()
 {
     //IL_000c: Unknown result type (might be due to invalid IL or missing references)
     //IL_0011: Expected O, but got Unknown
     //IL_007b: Unknown result type (might be due to invalid IL or missing references)
     //IL_00d5: Unknown result type (might be due to invalid IL or missing references)
     //IL_00da: Expected O, but got Unknown
     //IL_00fb: Unknown result type (might be due to invalid IL or missing references)
     //IL_0100: Expected O, but got Unknown
     //IL_010b: Unknown result type (might be due to invalid IL or missing references)
     //IL_0125: Unknown result type (might be due to invalid IL or missing references)
     //IL_012a: Expected O, but got Unknown
     //IL_014f: Unknown result type (might be due to invalid IL or missing references)
     //IL_015e: Unknown result type (might be due to invalid IL or missing references)
     //IL_0163: Unknown result type (might be due to invalid IL or missing references)
     //IL_0168: Unknown result type (might be due to invalid IL or missing references)
     //IL_017f: Unknown result type (might be due to invalid IL or missing references)
     //IL_0180: Unknown result type (might be due to invalid IL or missing references)
     //IL_0185: Unknown result type (might be due to invalid IL or missing references)
     //IL_018a: Unknown result type (might be due to invalid IL or missing references)
     //IL_018b: Unknown result type (might be due to invalid IL or missing references)
     //IL_018c: Unknown result type (might be due to invalid IL or missing references)
     //IL_018e: Unknown result type (might be due to invalid IL or missing references)
     //IL_0195: Unknown result type (might be due to invalid IL or missing references)
     //IL_019a: Unknown result type (might be due to invalid IL or missing references)
     //IL_01ac: Unknown result type (might be due to invalid IL or missing references)
     //IL_01b3: Expected O, but got Unknown
     //IL_01b3: Unknown result type (might be due to invalid IL or missing references)
     //IL_01b8: Unknown result type (might be due to invalid IL or missing references)
     //IL_01bc: Unknown result type (might be due to invalid IL or missing references)
     //IL_01c1: Unknown result type (might be due to invalid IL or missing references)
     //IL_01c4: Unknown result type (might be due to invalid IL or missing references)
     //IL_01c9: Unknown result type (might be due to invalid IL or missing references)
     //IL_01cb: Unknown result type (might be due to invalid IL or missing references)
     //IL_01d2: Unknown result type (might be due to invalid IL or missing references)
     //IL_01d7: Unknown result type (might be due to invalid IL or missing references)
     //IL_01de: Unknown result type (might be due to invalid IL or missing references)
     //IL_01e5: Unknown result type (might be due to invalid IL or missing references)
     //IL_01f0: Unknown result type (might be due to invalid IL or missing references)
     //IL_022e: Unknown result type (might be due to invalid IL or missing references)
     //IL_0233: Expected O, but got Unknown
     //IL_0244: Unknown result type (might be due to invalid IL or missing references)
     //IL_0254: Unknown result type (might be due to invalid IL or missing references)
     //IL_0259: Unknown result type (might be due to invalid IL or missing references)
     //IL_0284: Unknown result type (might be due to invalid IL or missing references)
     //IL_02bd: Unknown result type (might be due to invalid IL or missing references)
     //IL_03a7: Unknown result type (might be due to invalid IL or missing references)
     //IL_03d4: Unknown result type (might be due to invalid IL or missing references)
     //IL_03fa: Unknown result type (might be due to invalid IL or missing references)
     //IL_03ff: Unknown result type (might be due to invalid IL or missing references)
     //IL_0410: Unknown result type (might be due to invalid IL or missing references)
     //IL_0453: Unknown result type (might be due to invalid IL or missing references)
     //IL_0458: Unknown result type (might be due to invalid IL or missing references)
     //IL_046a: Unknown result type (might be due to invalid IL or missing references)
     //IL_046f: Expected O, but got Unknown
     //IL_0580: Unknown result type (might be due to invalid IL or missing references)
     //IL_0585: Expected O, but got Unknown
     //IL_05ac: Unknown result type (might be due to invalid IL or missing references)
     //IL_05b1: Unknown result type (might be due to invalid IL or missing references)
     //IL_05c1: Unknown result type (might be due to invalid IL or missing references)
     //IL_05ca: Unknown result type (might be due to invalid IL or missing references)
     //IL_05e1: Unknown result type (might be due to invalid IL or missing references)
     //IL_05e3: Unknown result type (might be due to invalid IL or missing references)
     //IL_05ef: Unknown result type (might be due to invalid IL or missing references)
     //IL_05f1: Unknown result type (might be due to invalid IL or missing references)
     //IL_074d: Unknown result type (might be due to invalid IL or missing references)
     //IL_074e: Unknown result type (might be due to invalid IL or missing references)
     //IL_0753: Unknown result type (might be due to invalid IL or missing references)
     //IL_0865: Unknown result type (might be due to invalid IL or missing references)
     //IL_08cb: Unknown result type (might be due to invalid IL or missing references)
     //IL_08d0: Expected O, but got Unknown
     //IL_08ea: Unknown result type (might be due to invalid IL or missing references)
     //IL_08eb: Unknown result type (might be due to invalid IL or missing references)
     //IL_08f0: Unknown result type (might be due to invalid IL or missing references)
     //IL_08fc: Unknown result type (might be due to invalid IL or missing references)
     //IL_08fd: Unknown result type (might be due to invalid IL or missing references)
     //IL_0902: Unknown result type (might be due to invalid IL or missing references)
     //IL_0905: Unknown result type (might be due to invalid IL or missing references)
     //IL_0906: Unknown result type (might be due to invalid IL or missing references)
     //IL_090b: Unknown result type (might be due to invalid IL or missing references)
     //IL_090e: Unknown result type (might be due to invalid IL or missing references)
     //IL_090f: Unknown result type (might be due to invalid IL or missing references)
     //IL_0914: Unknown result type (might be due to invalid IL or missing references)
     //IL_091b: Unknown result type (might be due to invalid IL or missing references)
     //IL_091c: Unknown result type (might be due to invalid IL or missing references)
     //IL_0921: Unknown result type (might be due to invalid IL or missing references)
     //IL_0922: Unknown result type (might be due to invalid IL or missing references)
     //IL_0927: Unknown result type (might be due to invalid IL or missing references)
     //IL_092c: Unknown result type (might be due to invalid IL or missing references)
     //IL_092f: Unknown result type (might be due to invalid IL or missing references)
     //IL_0934: Unknown result type (might be due to invalid IL or missing references)
     //IL_0936: Unknown result type (might be due to invalid IL or missing references)
     //IL_093b: Unknown result type (might be due to invalid IL or missing references)
     //IL_0963: Unknown result type (might be due to invalid IL or missing references)
     if (this.get_enabled() && NGUITools.GetActive(this.get_gameObject()) && mChild == null && atlas != null && isValid && items.Count > 0)
     {
         mLabelList.Clear();
         this.StopCoroutine("CloseIfUnselected");
         UICamera.selectedObject = (UICamera.hoveredObject ?? this.get_gameObject());
         mSelection = UICamera.selectedObject;
         source     = UICamera.selectedObject;
         if (source == null)
         {
             Debug.LogError((object)"Popup list needs a source object...");
         }
         else
         {
             mOpenFrame = Time.get_frameCount();
             if (mPanel == null)
             {
                 mPanel = UIPanel.Find(this.get_transform());
                 if (mPanel == null)
                 {
                     return;
                 }
             }
             mChild = new GameObject("Drop-down List");
             mChild.set_layer(this.get_gameObject().get_layer());
             current = this;
             Transform val = mChild.get_transform();
             val.set_parent(mPanel.cachedTransform);
             Vector3 val2;
             Vector3 val3;
             Vector3 val4;
             if (openOn == OpenOn.Manual && mSelection != this.get_gameObject())
             {
                 val2 = Vector2.op_Implicit(UICamera.lastEventPosition);
                 val3 = mPanel.cachedTransform.InverseTransformPoint(mPanel.anchorCamera.ScreenToWorldPoint(val2));
                 val4 = val3;
                 val.set_localPosition(val3);
                 val2 = val.get_position();
             }
             else
             {
                 Bounds val5 = NGUIMath.CalculateRelativeWidgetBounds(mPanel.cachedTransform, this.get_transform(), false, false);
                 val3 = val5.get_min();
                 val4 = val5.get_max();
                 val.set_localPosition(val3);
                 val2 = val.get_position();
             }
             this.StartCoroutine("CloseIfUnselected");
             val.set_localRotation(Quaternion.get_identity());
             val.set_localScale(Vector3.get_one());
             mBackground       = NGUITools.AddSprite(mChild, atlas, backgroundSprite);
             mBackground.pivot = UIWidget.Pivot.TopLeft;
             mBackground.depth = NGUITools.CalculateNextDepth(mPanel.get_gameObject());
             mBackground.color = backgroundColor;
             Vector4 border = mBackground.border;
             mBgBorder = border.y;
             mBackground.cachedTransform.set_localPosition(new Vector3(0f, border.y, 0f));
             mHighlight       = NGUITools.AddSprite(mChild, atlas, highlightSprite);
             mHighlight.pivot = UIWidget.Pivot.TopLeft;
             mHighlight.color = highlightColor;
             UISpriteData atlasSprite = mHighlight.GetAtlasSprite();
             if (atlasSprite != null)
             {
                 float          num             = (float)atlasSprite.borderTop;
                 float          num2            = (float)activeFontSize;
                 float          activeFontScale = this.activeFontScale;
                 float          num3            = num2 * activeFontScale;
                 float          num4            = 0f;
                 float          num5            = 0f - padding.y;
                 List <UILabel> list            = new List <UILabel>();
                 if (!items.Contains(mSelectedItem))
                 {
                     mSelectedItem = null;
                 }
                 int i = 0;
                 for (int count = items.Count; i < count; i++)
                 {
                     string  text    = items[i];
                     UILabel uILabel = NGUITools.AddWidget <UILabel>(mChild);
                     uILabel.set_name(i.ToString());
                     uILabel.pivot        = UIWidget.Pivot.TopLeft;
                     uILabel.bitmapFont   = bitmapFont;
                     uILabel.trueTypeFont = trueTypeFont;
                     uILabel.fontSize     = fontSize;
                     uILabel.fontStyle    = fontStyle;
                     uILabel.text         = ((!isLocalized) ? text : Localization.Get(text));
                     uILabel.color        = textColor;
                     object  cachedTransform = (object)uILabel.cachedTransform;
                     float   num6            = border.x + padding.x;
                     Vector2 pivotOffset     = uILabel.pivotOffset;
                     cachedTransform.set_localPosition(new Vector3(num6 - pivotOffset.x, num5, -1f));
                     uILabel.overflowMethod = UILabel.Overflow.ResizeFreely;
                     uILabel.alignment      = alignment;
                     list.Add(uILabel);
                     num5 -= num3;
                     num5 -= padding.y;
                     float   num7        = num4;
                     Vector2 printedSize = uILabel.printedSize;
                     num4 = Mathf.Max(num7, printedSize.x);
                     UIEventListener uIEventListener = UIEventListener.Get(uILabel.get_gameObject());
                     uIEventListener.onHover   = OnItemHover;
                     uIEventListener.onPress   = OnItemPress;
                     uIEventListener.parameter = text;
                     if (mSelectedItem == text || (i == 0 && string.IsNullOrEmpty(mSelectedItem)))
                     {
                         Highlight(uILabel, true);
                     }
                     mLabelList.Add(uILabel);
                 }
                 num4 = Mathf.Max(num4, val4.x - val3.x - (border.x + padding.x) * 2f);
                 float   num8 = num4;
                 Vector3 val6 = default(Vector3);
                 val6._002Ector(num8 * 0.5f, (0f - num3) * 0.5f, 0f);
                 Vector3 val7 = default(Vector3);
                 val7._002Ector(num8, num3 + padding.y, 1f);
                 int j = 0;
                 for (int count2 = list.Count; j < count2; j++)
                 {
                     UILabel uILabel2 = list[j];
                     NGUITools.AddWidgetCollider(uILabel2.get_gameObject());
                     uILabel2.autoResizeBoxCollider = false;
                     BoxCollider component = uILabel2.GetComponent <BoxCollider>();
                     if (component != null)
                     {
                         Vector3 center = component.get_center();
                         val6.z = center.z;
                         component.set_center(val6);
                         component.set_size(val7);
                     }
                     else
                     {
                         BoxCollider2D component2 = uILabel2.GetComponent <BoxCollider2D>();
                         component2.set_offset(Vector2.op_Implicit(val6));
                         component2.set_size(Vector2.op_Implicit(val7));
                     }
                 }
                 int width = Mathf.RoundToInt(num4);
                 num4 += (border.x + padding.x) * 2f;
                 num5 -= border.y;
                 mBackground.width  = Mathf.RoundToInt(num4);
                 mBackground.height = Mathf.RoundToInt(0f - num5 + border.y);
                 int k = 0;
                 for (int count3 = list.Count; k < count3; k++)
                 {
                     UILabel uILabel3 = list[k];
                     uILabel3.overflowMethod = UILabel.Overflow.ShrinkContent;
                     uILabel3.width          = width;
                 }
                 float num9  = 2f * atlas.pixelSize;
                 float num10 = num4 - (border.x + padding.x) * 2f + (float)atlasSprite.borderLeft * num9;
                 float num11 = num3 + num * num9;
                 mHighlight.width  = Mathf.RoundToInt(num10);
                 mHighlight.height = Mathf.RoundToInt(num11);
                 bool flag = position == Position.Above;
                 if (position == Position.Auto)
                 {
                     UICamera uICamera = UICamera.FindCameraForLayer(mSelection.get_layer());
                     if (uICamera != null)
                     {
                         Vector3 val8 = uICamera.cachedCamera.WorldToViewportPoint(val2);
                         flag = (val8.y < 0.5f);
                     }
                 }
                 if (isAnimated)
                 {
                     AnimateColor(mBackground);
                     if (Time.get_timeScale() == 0f || Time.get_timeScale() >= 0.1f)
                     {
                         float bottom = num5 + num3;
                         Animate(mHighlight, flag, bottom);
                         int l = 0;
                         for (int count4 = list.Count; l < count4; l++)
                         {
                             Animate(list[l], flag, bottom);
                         }
                         AnimateScale(mBackground, flag, bottom);
                     }
                 }
                 if (flag)
                 {
                     val3.y = val4.y - border.y;
                     val4.y = val3.y + (float)mBackground.height;
                     val4.x = val3.x + (float)mBackground.width;
                     val.set_localPosition(new Vector3(val3.x, val4.y - border.y, val3.z));
                 }
                 else
                 {
                     val4.y = val3.y + border.y;
                     val3.y = val4.y - (float)mBackground.height;
                     val4.x = val3.x + (float)mBackground.width;
                 }
                 Transform val9 = mPanel.cachedTransform.get_parent();
                 if (val9 != null)
                 {
                     val3 = mPanel.cachedTransform.TransformPoint(val3);
                     val4 = mPanel.cachedTransform.TransformPoint(val4);
                     val3 = val9.InverseTransformPoint(val3);
                     val4 = val9.InverseTransformPoint(val4);
                 }
                 Vector3 val10 = mPanel.CalculateConstrainOffset(Vector2.op_Implicit(val3), Vector2.op_Implicit(val4));
                 val2   = val.get_localPosition() + val10;
                 val2.x = Mathf.Round(val2.x);
                 val2.y = Mathf.Round(val2.y);
                 val.set_localPosition(val2);
             }
         }
     }
     else
     {
         OnSelect(false);
     }
 }
    /// <summary>
    /// Returns the object under the specified position.
    /// </summary>

    static public bool Raycast(Vector3 inPos, out RaycastHit hit)
    {
        for (int i = 0; i < list.Count; ++i)
        {
            UICamera cam = list[i];

            // Skip inactive scripts
            if (!cam.enabled || !NGUITools.GetActive(cam.gameObject))
            {
                continue;
            }

            // Convert to view space
            currentCamera = cam.cachedCamera;
            Vector3 pos = currentCamera.ScreenToViewportPoint(inPos);
            if (float.IsNaN(pos.x) || float.IsNaN(pos.y))
            {
                continue;
            }

            // If it's outside the camera's viewport, do nothing
            if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f)
            {
                continue;
            }

            // Cast a ray into the screen
            Ray ray = currentCamera.ScreenPointToRay(inPos);

            // Raycast into the screen
            int   mask = currentCamera.cullingMask & (int)cam.eventReceiverMask;
            float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane;

            if (cam.eventType == EventType.World)
            {
                if (Physics.Raycast(ray, out hit, dist, mask))
                {
                    hoveredObject = hit.collider.gameObject;
                    return(true);
                }
                continue;
            }
            else if (cam.eventType == EventType.UI)
            {
                RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask);

                if (hits.Length > 1)
                {
                    for (int b = 0; b < hits.Length; ++b)
                    {
                        GameObject go = hits[b].collider.gameObject;
                        mHit.depth = NGUITools.CalculateRaycastDepth(go);
                        mHit.hit   = hits[b];
                        mHits.Add(mHit);
                    }

                    mHits.Sort(delegate(DepthEntry r1, DepthEntry r2) { return(r2.depth.CompareTo(r1.depth)); });

                    for (int b = 0; b < mHits.size; ++b)
                    {
                        if (IsVisible(ref mHits.buffer[b]))
                        {
                            hit           = mHits[b].hit;
                            hoveredObject = hit.collider.gameObject;
                            mHits.Clear();
                            return(true);
                        }
                    }
                    mHits.Clear();
                }
                else if (hits.Length == 1 && IsVisible(ref hits[0]))
                {
                    hit           = hits[0];
                    hoveredObject = hit.collider.gameObject;
                    return(true);
                }
                continue;
            }
        }
        hit = mEmpty;
        return(false);
    }
예제 #12
0
    /// <summary>
    /// Show the popup list dialog.
    /// </summary>

    public virtual void Show()
    {
        if (enabled && NGUITools.GetActive(gameObject) && mChild == null && atlas != null && isValid && items.Count > 0)
        {
            mLabelList.Clear();
            StopCoroutine("CloseIfUnselected");

            // Ensure the popup's source has the selection
            UICamera.selectedObject = (UICamera.hoveredObject ?? gameObject);
            mSelection = UICamera.selectedObject;
            source     = UICamera.selectedObject;

            if (source == null)
            {
                Debug.LogError("Popup list needs a source object...");
                return;
            }

            mOpenFrame = Time.frameCount;

            // Automatically locate the panel responsible for this object
            if (mPanel == null)
            {
                mPanel = UIPanel.Find(transform);
                if (mPanel == null)
                {
                    return;
                }
            }

            // Calculate the dimensions of the object triggering the popup list so we can position it below it
            Vector3 min;
            Vector3 max;

            // Create the root object for the list
            mChild       = new GameObject("Drop-down List");
            mChild.layer = gameObject.layer;

            if (separatePanel)
            {
                if (GetComponent <Collider>() != null)
                {
                    Rigidbody rb = mChild.AddComponent <Rigidbody>();
                    rb.isKinematic = true;
                }
                else if (GetComponent <Collider2D>() != null)
                {
                    Rigidbody2D rb = mChild.AddComponent <Rigidbody2D>();
                    rb.isKinematic = true;
                }
                mChild.AddComponent <UIPanel>().depth = 1000000;
            }
            current = this;

            Transform t = mChild.transform;
            t.parent = mPanel.cachedTransform;
            Vector3 pos;

            // Manually triggered popup list on some other game object
            if (openOn == OpenOn.Manual && mSelection != gameObject)
            {
                pos             = UICamera.lastEventPosition;
                min             = mPanel.cachedTransform.InverseTransformPoint(mPanel.anchorCamera.ScreenToWorldPoint(pos));
                max             = min;
                t.localPosition = min;
                pos             = t.position;
            }
            else
            {
                Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(mPanel.cachedTransform, transform, false, false);
                min             = bounds.min;
                max             = bounds.max;
                t.localPosition = min;
                pos             = t.position;
            }


            StartCoroutine("CloseIfUnselected");

            //t.localRotation = Quaternion.identity;
            t.eulerAngles = gameObject.transform.eulerAngles;

            t.localScale = Vector3.one;

            // Add a sprite for the background
            mBackground       = NGUITools.AddSprite(mChild, atlas, backgroundSprite, separatePanel ? 0 : NGUITools.CalculateNextDepth(mPanel.gameObject));
            mBackground.pivot = UIWidget.Pivot.TopLeft;
            mBackground.color = backgroundColor;

            // We need to know the size of the background sprite for padding purposes
            Vector4 bgPadding = mBackground.border;
            mBgBorder = bgPadding.y;
            mBackground.cachedTransform.localPosition = new Vector3(0f, bgPadding.y, 0f);

            // Add a sprite used for the selection
            mHighlight       = NGUITools.AddSprite(mChild, atlas, highlightSprite, mBackground.depth + 1);
            mHighlight.pivot = UIWidget.Pivot.TopLeft;
            mHighlight.color = highlightColor;

            UISpriteData hlsp = mHighlight.GetAtlasSprite();
            if (hlsp == null)
            {
                return;
            }

            float          hlspHeight = hlsp.borderTop;
            float          fontHeight = activeFontSize;
            float          dynScale = activeFontScale;
            float          labelHeight = fontHeight * dynScale;
            float          x = 0f, y = -padding.y;
            List <UILabel> labels = new List <UILabel>();

            // Clear the selection if it's no longer present
            if (!items.Contains(mSelectedItem))
            {
                mSelectedItem = null;
            }

            // Run through all items and create labels for each one
            for (int i = 0, imax = items.Count; i < imax; ++i)
            {
                string s = items[i];

                UILabel lbl = NGUITools.AddWidget <UILabel>(mChild, mBackground.depth + 2);
                lbl.name         = i.ToString();
                lbl.pivot        = UIWidget.Pivot.TopLeft;
                lbl.bitmapFont   = bitmapFont;
                lbl.trueTypeFont = trueTypeFont;
                lbl.fontSize     = fontSize;
                lbl.fontStyle    = fontStyle;
                lbl.text         = isLocalized ? Localization.Get(s) : s;
                lbl.color        = textColor;
                lbl.cachedTransform.localPosition = new Vector3(bgPadding.x + padding.x - lbl.pivotOffset.x, y, -1f);
                lbl.overflowMethod = UILabel.Overflow.ResizeFreely;
                lbl.alignment      = alignment;
                labels.Add(lbl);

                y -= labelHeight;
                y -= padding.y;
                x  = Mathf.Max(x, lbl.printedSize.x);

                // Add an event listener
                UIEventListener listener = UIEventListener.Get(lbl.gameObject);
                listener.onHover  = OnItemHover;
                listener.onPress  = OnItemPress;
                listener.onScroll = OnItemScroll;

                listener.parameter = s;

                // Move the selection here if this is the right label
                if (mSelectedItem == s || (i == 0 && string.IsNullOrEmpty(mSelectedItem)))
                {
                    Highlight(lbl, true);
                }

                // Add this label to the list
                mLabelList.Add(lbl);
            }

            // The triggering widget's width should be the minimum allowed width
            x = Mathf.Max(x, (max.x - min.x) - (bgPadding.x + padding.x) * 2f);

            float   cx       = x;
            Vector3 bcCenter = new Vector3(cx * 0.5f, -labelHeight * 0.5f, 0f);
            Vector3 bcSize   = new Vector3(cx, (labelHeight + padding.y), 1f);

            // Run through all labels and add colliders
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel lbl = labels[i];
                NGUITools.AddWidgetCollider(lbl.gameObject);
                lbl.autoResizeBoxCollider = false;
                BoxCollider bc = lbl.GetComponent <BoxCollider>();

                if (bc != null)
                {
                    bcCenter.z = bc.center.z;
                    bc.center  = bcCenter;
                    bc.size    = bcSize;
                }
                else
                {
                    BoxCollider2D b2d = lbl.GetComponent <BoxCollider2D>();
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
                    b2d.center = bcCenter;
#else
                    b2d.offset = bcCenter;
#endif
                    b2d.size = bcSize;
                }
            }

            int lblWidth = Mathf.RoundToInt(x);
            x += (bgPadding.x + padding.x) * 2f;
            y -= bgPadding.y;

            // Scale the background sprite to envelop the entire set of items
            mBackground.width  = Mathf.RoundToInt(x);
            mBackground.height = Mathf.RoundToInt(-y + bgPadding.y);

            // Set the label width to make alignment work
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel lbl = labels[i];
                lbl.overflowMethod = UILabel.Overflow.ShrinkContent;
                lbl.width          = lblWidth;
            }

            // Scale the highlight sprite to envelop a single item
            float scaleFactor = 2f * atlas.pixelSize;
            float w           = x - (bgPadding.x + padding.x) * 2f + hlsp.borderLeft * scaleFactor;
            float h           = labelHeight + hlspHeight * scaleFactor;
            mHighlight.width  = Mathf.RoundToInt(w);
            mHighlight.height = Mathf.RoundToInt(h);

            bool placeAbove = (position == Position.Above);

            if (position == Position.Auto)
            {
                UICamera cam = UICamera.FindCameraForLayer(mSelection.layer);

                if (cam != null)
                {
                    Vector3 viewPos = cam.cachedCamera.WorldToViewportPoint(pos);
                    placeAbove = (viewPos.y < 0.5f);
                }
            }

            // If the list should be animated, let's animate it by expanding it
            if (isAnimated)
            {
                AnimateColor(mBackground);

                if (Time.timeScale == 0f || Time.timeScale >= 0.1f)
                {
                    float bottom = y + labelHeight;
                    Animate(mHighlight, placeAbove, bottom);
                    for (int i = 0, imax = labels.Count; i < imax; ++i)
                    {
                        Animate(labels[i], placeAbove, bottom);
                    }
                    AnimateScale(mBackground, placeAbove, bottom);
                }
            }

            // If we need to place the popup list above the item, we need to reposition everything by the size of the list
            if (placeAbove)
            {
                min.y           = max.y - bgPadding.y;
                max.y           = min.y + mBackground.height;
                max.x           = min.x + mBackground.width;
                t.localPosition = new Vector3(min.x, max.y - bgPadding.y, min.z);
            }
            else
            {
                max.y = min.y + bgPadding.y;
                min.y = max.y - mBackground.height;
                max.x = min.x + mBackground.width;
            }

            Transform pt = mPanel.cachedTransform.parent;

            if (pt != null)
            {
                min = mPanel.cachedTransform.TransformPoint(min);
                max = mPanel.cachedTransform.TransformPoint(max);
                min = pt.InverseTransformPoint(min);
                max = pt.InverseTransformPoint(max);
            }

            // Ensure that everything fits into the panel's visible range
            Vector3 offset = mPanel.hasClipping ? Vector3.zero : mPanel.CalculateConstrainOffset(min, max);
            pos             = t.localPosition + offset;
            pos.x           = Mathf.Round(pos.x);
            pos.y           = Mathf.Round(pos.y);
            t.localPosition = pos;
        }
        else
        {
            OnSelect(false);
        }
        if (mChild != null)
        {
            //if (gameObject.layer == Program.ui_back_ground_2d.layer)
            //{
            //    mChild.transform.SetParent(Program.ui_main_2d.transform, true);
            //    var trans = mChild.GetComponentsInChildren<Transform>();
            //    foreach (var item in trans)
            //    {
            //        item.gameObject.layer = Program.ui_main_2d.layer;
            //    }
            //}

            if (gameObject.layer == Program.ui_main_3d.layer)
            {
                mChild.transform.SetParent(Program.ui_main_3d.transform, true);
            }
            if (gameObject.layer == Program.ui_windows_2d.layer)
            {
                mChild.transform.SetParent(Program.ui_windows_2d.transform, true);
            }
            if (gameObject.layer == Program.ui_main_2d.layer)
            {
                mChild.transform.SetParent(Program.ui_main_2d.transform, true);
            }
        }
    }
예제 #13
0
    static void CalculateRelativeWidgetBounds(Transform content, bool considerInactive, bool isRoot,
                                              ref Matrix4x4 toLocal, ref Vector3 vMin, ref Vector3 vMax, ref bool isSet, bool considerParents)
    {
        if (content == null)
        {
            return;
        }
        if (!considerInactive && !NGUITools.GetActive(content.gameObject))
        {
            return;
        }

        // If this isn't a root node, check to see if there is a panel present
        UIPanel p = isRoot ? null : content.GetComponent <UIPanel>();

        // Ignore disabled panels as a disabled panel means invisible children
        if (p != null && !p.enabled)
        {
            return;
        }

        // If there is a clipped panel present simply include its dimensions
        if (p != null && p.clipping != UIDrawCall.Clipping.None)
        {
            Vector3[] corners = p.worldCorners;

            for (int j = 0; j < 4; ++j)
            {
                Vector3 v = toLocal.MultiplyPoint3x4(corners[j]);

                if (v.x > vMax.x)
                {
                    vMax.x = v.x;
                }
                if (v.y > vMax.y)
                {
                    vMax.y = v.y;
                }
                if (v.z > vMax.z)
                {
                    vMax.z = v.z;
                }

                if (v.x < vMin.x)
                {
                    vMin.x = v.x;
                }
                if (v.y < vMin.y)
                {
                    vMin.y = v.y;
                }
                if (v.z < vMin.z)
                {
                    vMin.z = v.z;
                }

                isSet = true;
            }
        }
        else         // No panel present
        {
            // If there is a widget present, include its bounds
            UIWidget w = content.GetComponent <UIWidget>();

            if (w != null && w.enabled)
            {
                Vector3[] corners = w.worldCorners;

                for (int j = 0; j < 4; ++j)
                {
                    Vector3 v = toLocal.MultiplyPoint3x4(corners[j]);

                    if (v.x > vMax.x)
                    {
                        vMax.x = v.x;
                    }
                    if (v.y > vMax.y)
                    {
                        vMax.y = v.y;
                    }
                    if (v.z > vMax.z)
                    {
                        vMax.z = v.z;
                    }

                    if (v.x < vMin.x)
                    {
                        vMin.x = v.x;
                    }
                    if (v.y < vMin.y)
                    {
                        vMin.y = v.y;
                    }
                    if (v.z < vMin.z)
                    {
                        vMin.z = v.z;
                    }

                    isSet = true;
                }

                if (!considerParents)
                {
                    return;
                }
            }

            for (int i = 0, imax = content.childCount; i < imax; ++i)
            {
                CalculateRelativeWidgetBounds(content.GetChild(i), considerInactive, false, ref toLocal, ref vMin, ref vMax, ref isSet, true);
            }
        }
    }
예제 #14
0
    /// <summary>
    /// Helper function that returns the selected root object.
    /// </summary>

    static public GameObject SelectedRoot(bool createIfMissing)
    {
        GameObject go = Selection.activeGameObject;

        // Only use active objects
        if (go != null && !NGUITools.GetActive(go))
        {
            go = null;
        }

        // Try to find a panel
        UIPanel p = (go != null) ? NGUITools.FindInParents <UIPanel>(go) : null;

        // No selection? Try to find the root automatically
        if (p == null)
        {
            UIPanel[] panels = NGUITools.FindActive <UIPanel>();
            if (panels.Length > 0)
            {
                go = panels[0].gameObject;
            }
        }

        // Now find the first uniformly scaled object
        if (go != null)
        {
            Transform t = go.transform;

            // Find the first uniformly scaled object
            while (!Mathf.Approximately(t.localScale.x, t.localScale.y) ||
                   !Mathf.Approximately(t.localScale.x, t.localScale.z))
            {
                t = t.parent;
                if (t == null)
                {
                    return((p != null) ? p.gameObject : null);
                }
                else
                {
                    go = t.gameObject;
                }
            }
        }

        if (createIfMissing && go == null)
        {
            // No object specified -- find the first panel
            if (go == null)
            {
                UIPanel panel = GameObject.FindObjectOfType(typeof(UIPanel)) as UIPanel;
                if (panel != null)
                {
                    go = panel.gameObject;
                }
            }

            // No UI present -- create a new one
            if (go == null)
            {
                go = UICreateNewUIWizard.CreateNewUI();
            }
        }
        return(go);
    }
예제 #15
0
 private void LateUpdate()
 {
     if (Application.isPlaying)
     {
         float deltaTime = RealTime.deltaTime;
         if (showScrollBars != 0 && ((bool)verticalScrollBar || (bool)horizontalScrollBar))
         {
             bool flag  = false;
             bool flag2 = false;
             if (showScrollBars != ShowCondition.WhenDragging || mDragID != -10 || mMomentum.magnitude > 0.01f)
             {
                 flag  = shouldMoveVertically;
                 flag2 = shouldMoveHorizontally;
             }
             if ((bool)verticalScrollBar)
             {
                 float alpha = verticalScrollBar.alpha;
                 alpha += ((!flag) ? ((0f - deltaTime) * 3f) : (deltaTime * 6f));
                 alpha  = Mathf.Clamp01(alpha);
                 if (verticalScrollBar.alpha != alpha)
                 {
                     verticalScrollBar.alpha = alpha;
                 }
             }
             if ((bool)horizontalScrollBar)
             {
                 float alpha2 = horizontalScrollBar.alpha;
                 alpha2 += ((!flag2) ? ((0f - deltaTime) * 3f) : (deltaTime * 6f));
                 alpha2  = Mathf.Clamp01(alpha2);
                 if (horizontalScrollBar.alpha != alpha2)
                 {
                     horizontalScrollBar.alpha = alpha2;
                 }
             }
         }
         if (mShouldMove)
         {
             if (!mPressed)
             {
                 if (mMomentum.magnitude > 0.0001f || mScroll != 0f)
                 {
                     if (movement == Movement.Horizontal)
                     {
                         mMomentum -= mTrans.TransformDirection(new Vector3(mScroll * 0.05f, 0f, 0f));
                     }
                     else if (movement == Movement.Vertical)
                     {
                         mMomentum -= mTrans.TransformDirection(new Vector3(0f, mScroll * 0.05f, 0f));
                     }
                     else if (movement == Movement.Unrestricted)
                     {
                         mMomentum -= mTrans.TransformDirection(new Vector3(mScroll * 0.05f, mScroll * 0.05f, 0f));
                     }
                     else
                     {
                         mMomentum -= mTrans.TransformDirection(new Vector3(mScroll * customMovement.x * 0.05f, mScroll * customMovement.y * 0.05f, 0f));
                     }
                     mScroll = NGUIMath.SpringLerp(mScroll, 0f, 20f, deltaTime);
                     Vector3 absolute = NGUIMath.SpringDampen(ref mMomentum, 9f, deltaTime);
                     MoveAbsolute(absolute);
                     if (restrictWithinPanel && mPanel.clipping != 0)
                     {
                         if (NGUITools.GetActive(centerOnChild))
                         {
                             if (centerOnChild.nextPageThreshold != 0f)
                             {
                                 mMomentum = Vector3.zero;
                                 mScroll   = 0f;
                             }
                             else
                             {
                                 centerOnChild.Recenter();
                             }
                         }
                         else
                         {
                             RestrictWithinBounds(/*instant:*/ false, canMoveHorizontally, canMoveVertically);
                         }
                     }
                     if (onMomentumMove != null)
                     {
                         onMomentumMove();
                     }
                 }
                 else
                 {
                     mScroll   = 0f;
                     mMomentum = Vector3.zero;
                     SpringPanel component = GetComponent <SpringPanel>();
                     if (!(component != null) || !component.enabled)
                     {
                         mShouldMove = false;
                         if (onStoppedMoving != null)
                         {
                             onStoppedMoving();
                         }
                     }
                 }
             }
             else
             {
                 mScroll = 0f;
                 NGUIMath.SpringDampen(ref mMomentum, 9f, deltaTime);
             }
         }
     }
 }
예제 #16
0
    /// <summary>
    /// Draw the custom wizard.
    /// </summary>

    void OnGUI()
    {
        List <UIPanel> panels = GetListOfPanels();

        if (panels != null && panels.Count > 0)
        {
            UIPanel selectedPanel = NGUITools.FindInParents <UIPanel>(Selection.activeGameObject);

            // First, collect a list of panels with their associated widgets
            List <Entry> entries       = new List <Entry>();
            Entry        selectedEntry = null;
            bool         allEnabled    = true;

            foreach (UIPanel panel in panels)
            {
                Entry ent = new Entry();
                ent.panel          = panel;
                ent.widgets        = GetWidgets(panel);
                ent.isEnabled      = panel.enabled && NGUITools.GetActive(panel.gameObject);
                ent.widgetsEnabled = ent.isEnabled;

                if (ent.widgetsEnabled)
                {
                    foreach (UIWidget w in ent.widgets)
                    {
                        if (!NGUITools.GetActive(w.gameObject))
                        {
                            allEnabled         = false;
                            ent.widgetsEnabled = false;
                            break;
                        }
                    }
                }
                else
                {
                    allEnabled = false;
                }
                entries.Add(ent);
            }

            // Sort the list by depth
            entries.Sort(Compare);

            mScroll = GUILayout.BeginScrollView(mScroll);

            NGUIEditorTools.SetLabelWidth(80f);
            bool showAll = DrawRow(null, null, allEnabled);
            NGUIEditorTools.DrawSeparator();

            foreach (Entry ent in entries)
            {
                if (DrawRow(ent, selectedPanel, ent.widgetsEnabled))
                {
                    selectedEntry = ent;
                }
            }

            GUILayout.EndScrollView();

            if (showAll)
            {
                foreach (Entry ent in entries)
                {
                    NGUITools.SetActive(ent.panel.gameObject, !allEnabled);
                }
            }
            else if (selectedEntry != null)
            {
                NGUITools.SetActive(selectedEntry.panel.gameObject, !selectedEntry.widgetsEnabled);
            }
        }
        else
        {
            GUILayout.Label("No UI Panels found in the scene");
        }
    }
예제 #17
0
파일: UIToggle.cs 프로젝트: yamido001/AStar
    /// <summary>
    /// Fade out or fade in the active sprite and notify the OnChange event listener.
    /// </summary>

    void Set(bool state)
    {
        if (!mStarted)
        {
            mIsActive    = state;
            startsActive = state;
            if (activeSprite != null)
            {
                activeSprite.alpha = state ? 1f : 0f;
            }
        }
        else if (mIsActive != state)
        {
            // Uncheck all other toggles
            if (group != 0 && state)
            {
                for (int i = 0, imax = list.size; i < imax;)
                {
                    UIToggle cb = list[i];
                    if (cb != this && cb.group == group)
                    {
                        cb.Set(false);
                    }

                    if (list.size != imax)
                    {
                        imax = list.size;
                        i    = 0;
                    }
                    else
                    {
                        ++i;
                    }
                }
            }

            // Remember the state
            mIsActive = state;

            // Tween the color of the active sprite
            if (activeSprite != null)
            {
                if (instantTween || !NGUITools.GetActive(this))
                {
                    activeSprite.alpha = mIsActive ? 1f : 0f;
                }
                else
                {
                    TweenAlpha.Begin(activeSprite.gameObject, 0.15f, mIsActive ? 1f : 0f);
                }
            }

            if (current == null)
            {
                current = this;

                if (EventDelegate.IsValid(onChange))
                {
                    EventDelegate.Execute(onChange);
                }
                else if (eventReceiver != null && !string.IsNullOrEmpty(functionName))
                {
                    // Legacy functionality support (for backwards compatibility)
                    eventReceiver.SendMessage(functionName, mIsActive, SendMessageOptions.DontRequireReceiver);
                }
                current = null;
            }

            // Play the checkmark animation
            if (activeAnimation != null)
            {
                ActiveAnimation aa = ActiveAnimation.Play(activeAnimation, null,
                                                          state ? Direction.Forward : Direction.Reverse,
                                                          EnableCondition.IgnoreDisabledState,
                                                          DisableCondition.DoNotDisable);
                if (instantTween || !NGUITools.GetActive(this))
                {
                    aa.Finish();
                }
            }
        }
    }
예제 #18
0
 public void Show()
 {
     if (base.enabled && NGUITools.GetActive(base.gameObject) && mChild == null && atlas != null && isValid && items.Count > 0)
     {
         mLabelList.Clear();
         if (mPanel == null)
         {
             mPanel = UIPanel.Find(base.transform);
             if (mPanel == null)
             {
                 return;
             }
         }
         handleEvents = true;
         Transform transform = base.transform;
         Bounds    bounds    = NGUIMath.CalculateRelativeWidgetBounds(transform.parent, transform);
         mChild       = new GameObject("Drop-down List");
         mChild.layer = base.gameObject.layer;
         Transform transform2 = mChild.transform;
         transform2.parent        = transform.parent;
         transform2.localPosition = bounds.min;
         transform2.localRotation = Quaternion.identity;
         transform2.localScale    = Vector3.one;
         mBackground       = NGUITools.AddSprite(mChild, atlas, backgroundSprite);
         mBackground.pivot = UIWidget.Pivot.TopLeft;
         mBackground.depth = NGUITools.CalculateNextDepth(mPanel.gameObject);
         mBackground.color = backgroundColor;
         Vector4 border = mBackground.border;
         mBgBorder = border.y;
         mBackground.cachedTransform.localPosition = new Vector3(0f, border.y, 0f);
         mHighlight       = NGUITools.AddSprite(mChild, atlas, highlightSprite);
         mHighlight.pivot = UIWidget.Pivot.TopLeft;
         mHighlight.color = highlightColor;
         UISpriteData atlasSprite = mHighlight.GetAtlasSprite();
         if (atlasSprite != null)
         {
             float          num             = (float)atlasSprite.borderTop;
             float          num2            = (float)activeFontSize;
             float          activeFontScale = this.activeFontScale;
             float          num3            = num2 * activeFontScale;
             float          num4            = 0f;
             float          num5            = 0f - padding.y;
             List <UILabel> list            = new List <UILabel>();
             if (!items.Contains(mSelectedItem))
             {
                 mSelectedItem = null;
             }
             int i = 0;
             for (int count = items.Count; i < count; i++)
             {
                 string  text    = items[i];
                 UILabel uILabel = NGUITools.AddWidget <UILabel>(mChild);
                 uILabel.name         = i.ToString();
                 uILabel.pivot        = UIWidget.Pivot.TopLeft;
                 uILabel.bitmapFont   = bitmapFont;
                 uILabel.trueTypeFont = trueTypeFont;
                 uILabel.fontSize     = fontSize;
                 uILabel.fontStyle    = fontStyle;
                 uILabel.text         = ((!isLocalized) ? text : Localization.Get(text));
                 uILabel.color        = textColor;
                 Transform cachedTransform = uILabel.cachedTransform;
                 float     num6            = border.x + padding.x;
                 Vector2   pivotOffset     = uILabel.pivotOffset;
                 cachedTransform.localPosition = new Vector3(num6 - pivotOffset.x, num5, -1f);
                 uILabel.overflowMethod        = UILabel.Overflow.ResizeFreely;
                 uILabel.alignment             = alignment;
                 list.Add(uILabel);
                 num5 -= num3;
                 num5 -= padding.y;
                 float   a           = num4;
                 Vector2 printedSize = uILabel.printedSize;
                 num4 = Mathf.Max(a, printedSize.x);
                 UIEventListener uIEventListener = UIEventListener.Get(uILabel.gameObject);
                 uIEventListener.onHover   = OnItemHover;
                 uIEventListener.onPress   = OnItemPress;
                 uIEventListener.onClick   = OnItemClick;
                 uIEventListener.parameter = text;
                 if (mSelectedItem == text || (i == 0 && string.IsNullOrEmpty(mSelectedItem)))
                 {
                     Highlight(uILabel, instant: true);
                 }
                 mLabelList.Add(uILabel);
             }
             float   a2   = num4;
             Vector3 size = bounds.size;
             num4 = Mathf.Max(a2, size.x * activeFontScale - (border.x + padding.x) * 2f);
             float   num7    = num4;
             Vector3 vector  = new Vector3(num7 * 0.5f, (0f - num2) * 0.5f, 0f);
             Vector3 vector2 = new Vector3(num7, num3 + padding.y, 1f);
             int     j       = 0;
             for (int count2 = list.Count; j < count2; j++)
             {
                 UILabel uILabel2 = list[j];
                 NGUITools.AddWidgetCollider(uILabel2.gameObject);
                 uILabel2.autoResizeBoxCollider = false;
                 BoxCollider component = uILabel2.GetComponent <BoxCollider>();
                 if (component != null)
                 {
                     Vector3 center = component.center;
                     vector.z         = center.z;
                     component.center = vector;
                     component.size   = vector2;
                 }
                 else
                 {
                     BoxCollider2D component2 = uILabel2.GetComponent <BoxCollider2D>();
                     component2.offset = vector;
                     component2.size   = vector2;
                 }
             }
             int width = Mathf.RoundToInt(num4);
             num4 += (border.x + padding.x) * 2f;
             num5 -= border.y;
             mBackground.width  = Mathf.RoundToInt(num4);
             mBackground.height = Mathf.RoundToInt(0f - num5 + border.y);
             int k = 0;
             for (int count3 = list.Count; k < count3; k++)
             {
                 UILabel uILabel3 = list[k];
                 uILabel3.overflowMethod = UILabel.Overflow.ShrinkContent;
                 uILabel3.width          = width;
             }
             float num8 = 2f * atlas.pixelSize;
             float f    = num4 - (border.x + padding.x) * 2f + (float)atlasSprite.borderLeft * num8;
             float f2   = num3 + num * num8;
             mHighlight.width  = Mathf.RoundToInt(f);
             mHighlight.height = Mathf.RoundToInt(f2);
             bool flag = position == Position.Above;
             if (position == Position.Auto)
             {
                 UICamera uICamera = UICamera.FindCameraForLayer(base.gameObject.layer);
                 if (uICamera != null)
                 {
                     Vector3 vector3 = uICamera.cachedCamera.WorldToViewportPoint(transform.position);
                     flag = (vector3.y < 0.5f);
                 }
             }
             if (isAnimated)
             {
                 float bottom = num5 + num3;
                 Animate(mHighlight, flag, bottom);
                 int l = 0;
                 for (int count4 = list.Count; l < count4; l++)
                 {
                     Animate(list[l], flag, bottom);
                 }
                 AnimateColor(mBackground);
                 AnimateScale(mBackground, flag, bottom);
             }
             if (flag)
             {
                 Transform transform3 = transform2;
                 Vector3   min        = bounds.min;
                 float     x          = min.x;
                 Vector3   max        = bounds.max;
                 float     y          = max.y - num5 - border.y;
                 Vector3   min2       = bounds.min;
                 transform3.localPosition = new Vector3(x, y, min2.z);
             }
         }
     }
     else
     {
         OnSelect(isSelected: false);
     }
 }
    // Token: 0x060002AD RID: 685 RVA: 0x0001AA7C File Offset: 0x00018C7C
    public virtual void Show()
    {
        if (!base.enabled || !NGUITools.GetActive(base.gameObject) || !(UIPopupList.mChild == null) || !this.isValid || this.items.Count <= 0)
        {
            this.OnSelect(false);
            return;
        }
        this.mLabelList.Clear();
        base.StopCoroutine("CloseIfUnselected");
        UICamera.selectedObject = (UICamera.hoveredObject ?? base.gameObject);
        this.mSelection         = UICamera.selectedObject;
        this.source             = this.mSelection;
        if (this.source == null)
        {
            Debug.LogError("Popup list needs a source object...");
            return;
        }
        this.mOpenFrame = Time.frameCount;
        if (this.mPanel == null)
        {
            this.mPanel = UIPanel.Find(base.transform);
            if (this.mPanel == null)
            {
                return;
            }
        }
        UIPopupList.mChild       = new GameObject("Drop-down List");
        UIPopupList.mChild.layer = base.gameObject.layer;
        if (this.separatePanel)
        {
            if (base.GetComponent <Collider>() != null)
            {
                UIPopupList.mChild.AddComponent <Rigidbody>().isKinematic = true;
            }
            else if (base.GetComponent <Collider2D>() != null)
            {
                UIPopupList.mChild.AddComponent <Rigidbody2D>().isKinematic = true;
            }
            UIPanel uipanel = UIPopupList.mChild.AddComponent <UIPanel>();
            uipanel.depth        = 1000000;
            uipanel.sortingOrder = this.mPanel.sortingOrder;
        }
        UIPopupList.current = this;
        Transform cachedTransform = this.mPanel.cachedTransform;
        Transform transform       = UIPopupList.mChild.transform;

        transform.parent = cachedTransform;
        Transform parent = cachedTransform;

        if (this.separatePanel)
        {
            UIRoot uiroot = this.mPanel.GetComponentInParent <UIRoot>();
            if (uiroot == null && UIRoot.list.Count != 0)
            {
                uiroot = UIRoot.list[0];
            }
            if (uiroot != null)
            {
                parent = uiroot.transform;
            }
        }
        Vector3 vector;
        Vector3 vector2;

        if (this.openOn == UIPopupList.OpenOn.Manual && this.mSelection != base.gameObject)
        {
            this.startingPosition = UICamera.lastEventPosition;
            vector  = cachedTransform.InverseTransformPoint(this.mPanel.anchorCamera.ScreenToWorldPoint(this.startingPosition));
            vector2 = vector;
            transform.localPosition = vector;
            this.startingPosition   = transform.position;
        }
        else
        {
            Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(cachedTransform, base.transform, false, false);
            vector  = bounds.min;
            vector2 = bounds.max;
            transform.localPosition = vector;
            this.startingPosition   = transform.position;
        }
        base.StartCoroutine("CloseIfUnselected");
        float fitScale = this.fitScale;

        transform.localRotation = Quaternion.identity;
        transform.localScale    = new Vector3(fitScale, fitScale, fitScale);
        int num = this.separatePanel ? 0 : NGUITools.CalculateNextDepth(this.mPanel.gameObject);

        if (this.background2DSprite != null)
        {
            UI2DSprite ui2DSprite = UIPopupList.mChild.AddWidget(num);
            ui2DSprite.sprite2D = this.background2DSprite;
            this.mBackground    = ui2DSprite;
        }
        else
        {
            if (!(this.atlas != null))
            {
                return;
            }
            this.mBackground = UIPopupList.mChild.AddSprite(this.atlas as INGUIAtlas, this.backgroundSprite, num);
        }
        bool flag = this.position == UIPopupList.Position.Above;

        if (this.position == UIPopupList.Position.Auto)
        {
            UICamera uicamera = UICamera.FindCameraForLayer(this.mSelection.layer);
            if (uicamera != null)
            {
                flag = (uicamera.cachedCamera.WorldToViewportPoint(this.startingPosition).y < 0.5f);
            }
        }
        this.mBackground.pivot = UIWidget.Pivot.TopLeft;
        this.mBackground.color = this.backgroundColor;
        Vector4 border = this.mBackground.border;

        this.mBgBorder = border.y;
        this.mBackground.cachedTransform.localPosition = new Vector3(0f, flag ? (border.y * 2f - (float)this.overlap) : ((float)this.overlap), 0f);
        if (this.highlight2DSprite != null)
        {
            UI2DSprite ui2DSprite2 = UIPopupList.mChild.AddWidget(num + 1);
            ui2DSprite2.sprite2D = this.highlight2DSprite;
            this.mHighlight      = ui2DSprite2;
        }
        else
        {
            if (!(this.atlas != null))
            {
                return;
            }
            this.mHighlight = UIPopupList.mChild.AddSprite(this.atlas as INGUIAtlas, this.highlightSprite, num + 1);
        }
        float num2 = 0f;
        float num3 = 0f;

        if (this.mHighlight.hasBorder)
        {
            num2 = this.mHighlight.border.w;
            num3 = this.mHighlight.border.x;
        }
        this.mHighlight.pivot = UIWidget.Pivot.TopLeft;
        this.mHighlight.color = this.highlightColor;
        float          num4 = (float)this.activeFontSize * this.activeFontScale;
        float          num5 = num4 + this.padding.y;
        float          num6 = 0f;
        float          num7 = flag ? (border.y - this.padding.y - (float)this.overlap) : (-this.padding.y - border.y + (float)this.overlap);
        float          num8 = border.y * 2f + this.padding.y;
        List <UILabel> list = new List <UILabel>();

        if (!this.items.Contains(this.mSelectedItem))
        {
            this.mSelectedItem = null;
        }
        int i     = 0;
        int count = this.items.Count;

        while (i < count)
        {
            string  text    = this.items[i];
            UILabel uilabel = UIPopupList.mChild.AddWidget(this.mBackground.depth + 2);
            uilabel.name         = i.ToString();
            uilabel.pivot        = UIWidget.Pivot.TopLeft;
            uilabel.bitmapFont   = (this.bitmapFont as INGUIFont);
            uilabel.trueTypeFont = this.trueTypeFont;
            uilabel.fontSize     = this.fontSize;
            uilabel.fontStyle    = this.fontStyle;
            uilabel.text         = (this.isLocalized ? Localization.Get(text, true) : text);
            uilabel.modifier     = this.textModifier;
            uilabel.color        = this.textColor;
            uilabel.cachedTransform.localPosition = new Vector3(border.x + this.padding.x - uilabel.pivotOffset.x, num7, -1f);
            uilabel.overflowMethod = UILabel.Overflow.ResizeFreely;
            uilabel.alignment      = this.alignment;
            uilabel.symbolStyle    = NGUIText.SymbolStyle.Colored;
            list.Add(uilabel);
            num8 += num5;
            num7 -= num5;
            num6  = Mathf.Max(num6, uilabel.printedSize.x);
            UIEventListener uieventListener = UIEventListener.Get(uilabel.gameObject);
            uieventListener.onHover   = new UIEventListener.BoolDelegate(this.OnItemHover);
            uieventListener.onPress   = new UIEventListener.BoolDelegate(this.OnItemPress);
            uieventListener.onClick   = new UIEventListener.VoidDelegate(this.OnItemClick);
            uieventListener.parameter = text;
            if (this.mSelectedItem == text || (i == 0 && string.IsNullOrEmpty(this.mSelectedItem)))
            {
                this.Highlight(uilabel, true);
            }
            this.mLabelList.Add(uilabel);
            i++;
        }
        num6 = Mathf.Max(num6, vector2.x - vector.x - (border.x + this.padding.x) * 2f);
        float   num9    = num6;
        Vector3 vector3 = new Vector3(num9 * 0.5f, -num4 * 0.5f, 0f);
        Vector3 vector4 = new Vector3(num9, num4 + this.padding.y, 1f);
        int     j       = 0;
        int     count2  = list.Count;

        while (j < count2)
        {
            UILabel uilabel2 = list[j];
            NGUITools.AddWidgetCollider(uilabel2.gameObject);
            uilabel2.autoResizeBoxCollider = false;
            BoxCollider component = uilabel2.GetComponent <BoxCollider>();
            if (component != null)
            {
                vector3.z        = component.center.z;
                component.center = vector3;
                component.size   = vector4;
            }
            else
            {
                BoxCollider2D component2 = uilabel2.GetComponent <BoxCollider2D>();
                component2.offset = vector3;
                component2.size   = vector4;
            }
            j++;
        }
        int width = Mathf.RoundToInt(num6);

        num6 += (border.x + this.padding.x) * 2f;
        num7 -= border.y;
        this.mBackground.width  = Mathf.RoundToInt(num6);
        this.mBackground.height = Mathf.RoundToInt(num8);
        int k      = 0;
        int count3 = list.Count;

        while (k < count3)
        {
            UILabel uilabel3 = list[k];
            uilabel3.overflowMethod = UILabel.Overflow.ShrinkContent;
            uilabel3.width          = width;
            k++;
        }
        float      num10      = 2f;
        INGUIAtlas inguiatlas = this.atlas as INGUIAtlas;

        if (inguiatlas != null)
        {
            num10 *= inguiatlas.pixelSize;
        }
        float f  = num6 - (border.x + this.padding.x) * 2f + num3 * num10;
        float f2 = num4 + num2 * num10;

        this.mHighlight.width  = Mathf.RoundToInt(f);
        this.mHighlight.height = Mathf.RoundToInt(f2);
        if (this.isAnimated)
        {
            this.AnimateColor(this.mBackground);
            if (Time.timeScale == 0f || Time.timeScale >= 0.1f)
            {
                float bottom = num7 + num4;
                this.Animate(this.mHighlight, flag, bottom);
                int l      = 0;
                int count4 = list.Count;
                while (l < count4)
                {
                    this.Animate(list[l], flag, bottom);
                    l++;
                }
                this.AnimateScale(this.mBackground, flag, bottom);
            }
        }
        if (flag)
        {
            float num11 = border.y * fitScale;
            vector.y  = vector2.y - border.y * fitScale;
            vector2.y = vector.y + ((float)this.mBackground.height - border.y * 2f) * fitScale;
            vector2.x = vector.x + (float)this.mBackground.width * fitScale;
            transform.localPosition = new Vector3(vector.x, vector2.y - num11, vector.z);
        }
        else
        {
            vector2.y = vector.y + border.y * fitScale;
            vector.y  = vector2.y - (float)this.mBackground.height * fitScale;
            vector2.x = vector.x + (float)this.mBackground.width * fitScale;
        }
        UIPanel uipanel2 = this.mPanel;

        for (;;)
        {
            UIRect parent2 = uipanel2.parent;
            if (parent2 == null)
            {
                break;
            }
            UIPanel componentInParent = parent2.GetComponentInParent <UIPanel>();
            if (componentInParent == null)
            {
                break;
            }
            uipanel2 = componentInParent;
        }
        if (cachedTransform != null)
        {
            vector  = cachedTransform.TransformPoint(vector);
            vector2 = cachedTransform.TransformPoint(vector2);
            vector  = uipanel2.cachedTransform.InverseTransformPoint(vector);
            vector2 = uipanel2.cachedTransform.InverseTransformPoint(vector2);
            float pixelSizeAdjustment = UIRoot.GetPixelSizeAdjustment(base.gameObject);
            vector  /= pixelSizeAdjustment;
            vector2 /= pixelSizeAdjustment;
        }
        Vector3 b       = uipanel2.CalculateConstrainOffset(vector, vector2);
        Vector3 vector5 = transform.localPosition + b;

        vector5.x = Mathf.Round(vector5.x);
        vector5.y = Mathf.Round(vector5.y);
        transform.localPosition = vector5;
        transform.parent        = parent;
    }
예제 #20
0
    /// <summary>
    /// Helper function used to print things in columns.
    /// </summary>

    void DrawRow(Camera cam)
    {
        bool highlight = (cam == null || Selection.activeGameObject == null) ? false :
                         (0 != (cam.cullingMask & (1 << Selection.activeGameObject.layer)));

        if (cam != null)
        {
            GUI.backgroundColor = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f);
            GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
            GUI.backgroundColor = Color.white;
        }
        else
        {
            GUILayout.BeginHorizontal();
        }

        bool enabled = (cam == null || (NGUITools.GetActive(cam.gameObject) && cam.enabled));

        GUI.color = Color.white;

        if (cam != null)
        {
            if (enabled != EditorGUILayout.Toggle(enabled, GUILayout.Width(20f)))
            {
                cam.enabled = !enabled;
                EditorUtility.SetDirty(cam.gameObject);
            }
        }
        else
        {
            GUILayout.Space(30f);
        }

        if (enabled)
        {
            GUI.color = highlight ? new Color(0f, 0.8f, 1f) : Color.white;
        }
        else
        {
            GUI.color = highlight ? new Color(0f, 0.5f, 0.8f) : Color.grey;
        }

        string camName, camLayer;

        if (cam == null)
        {
            camName  = "Camera's Name";
            camLayer = "Layer";
        }
        else
        {
            camName  = cam.name + (cam.orthographic ? " (2D)" : " (3D)");
            camLayer = LayerMask.LayerToName(cam.gameObject.layer);
        }

        if (GUILayout.Button(camName, EditorStyles.label, GUILayout.MinWidth(100f)) && cam != null)
        {
            Selection.activeGameObject = cam.gameObject;
            EditorUtility.SetDirty(cam.gameObject);
        }
        GUILayout.Label(camLayer, GUILayout.Width(70f));

        GUI.color = enabled ? Color.white : new Color(0.7f, 0.7f, 0.7f);

        if (cam == null)
        {
            GUILayout.Label("EV", GUILayout.Width(26f));
        }
        else
        {
            UICamera uic = cam.GetComponent <UICamera>();
            bool     ev  = (uic != null && uic.enabled);

            if (ev != EditorGUILayout.Toggle(ev, GUILayout.Width(20f)))
            {
                if (uic == null)
                {
                    uic = cam.gameObject.AddComponent <UICamera>();
                }
                uic.enabled = !ev;
            }
        }

        if (cam == null)
        {
            GUILayout.Label("Mask", GUILayout.Width(100f));
        }
        else
        {
            int mask = LayerMaskField(cam.cullingMask, GUILayout.Width(105f));

            if (cam.cullingMask != mask)
            {
                NGUIEditorTools.RegisterUndo("Camera Mask Change", cam);
                cam.cullingMask = mask;
            }
        }
        GUILayout.EndHorizontal();
    }
예제 #21
0
    // Token: 0x060030FF RID: 12543 RVA: 0x000F0328 File Offset: 0x000EE728
    public void Play(bool forward)
    {
        this.mActive = 0;
        GameObject gameObject = (!(this.tweenTarget == null)) ? this.tweenTarget : base.gameObject;

        if (!NGUITools.GetActive(gameObject))
        {
            if (this.ifDisabledOnPlay != EnableCondition.EnableThenPlay)
            {
                return;
            }
            NGUITools.SetActive(gameObject, true);
        }
        this.mTweens = ((!this.includeChildren) ? gameObject.GetComponents <UITweener>() : gameObject.GetComponentsInChildren <UITweener>());
        if (this.mTweens.Length == 0)
        {
            if (this.disableWhenFinished != DisableCondition.DoNotDisable)
            {
                NGUITools.SetActive(this.tweenTarget, false);
            }
        }
        else
        {
            bool flag = false;
            if (this.playDirection == Direction.Reverse)
            {
                forward = !forward;
            }
            int i   = 0;
            int num = this.mTweens.Length;
            while (i < num)
            {
                UITweener uitweener = this.mTweens[i];
                if (uitweener.tweenGroup == this.tweenGroup)
                {
                    if (!flag && !NGUITools.GetActive(gameObject))
                    {
                        flag = true;
                        NGUITools.SetActive(gameObject, true);
                    }
                    this.mActive++;
                    if (this.playDirection == Direction.Toggle)
                    {
                        EventDelegate.Add(uitweener.onFinished, new EventDelegate.Callback(this.OnFinished), true);
                        uitweener.Toggle();
                    }
                    else
                    {
                        if (this.resetOnPlay || (this.resetIfDisabled && !uitweener.enabled))
                        {
                            uitweener.Play(forward);
                            uitweener.ResetToBeginning();
                        }
                        EventDelegate.Add(uitweener.onFinished, new EventDelegate.Callback(this.OnFinished), true);
                        uitweener.Play(forward);
                    }
                }
                i++;
            }
        }
    }
    /// <summary>
    /// Create a plane on which we will be performing the dragging.
    /// </summary>

    public void Press(bool pressed)
    {
        if (UICamera.currentScheme == UICamera.ControlScheme.Controller)
        {
            return;
        }

        if (smoothDragStart && pressed)
        {
            mDragStarted     = false;
            mDragStartOffset = Vector2.zero;
        }

        if (enabled && NGUITools.GetActive(gameObject))
        {
            if (!pressed && mDragID == UICamera.currentTouchID)
            {
                mDragID = -10;
            }

            mCalculatedBounds = false;
            mShouldMove       = shouldMove;
            if (!mShouldMove)
            {
                return;
            }
            mPressed = pressed;

            if (pressed)
            {
                // Remove all momentum on press
                mMomentum = Vector3.zero;
                mScroll   = 0f;

                // Disable the spring movement
                DisableSpring();

                // Remember the hit position
                mLastPos = UICamera.lastWorldPosition;

                // Create the plane to drag along
                mPlane = new Plane(mTrans.rotation * Vector3.back, mLastPos);

                // Ensure that we're working with whole numbers, keeping everything pixel-perfect
                Vector2 co = mPanel.clipOffset;
                co.x = Mathf.Round(co.x);
                co.y = Mathf.Round(co.y);
                mPanel.clipOffset = co;

                Vector3 v = mTrans.localPosition;
                v.x = Mathf.Round(v.x);
                v.y = Mathf.Round(v.y);
                mTrans.localPosition = v;

                if (!smoothDragStart)
                {
                    mDragStarted     = true;
                    mDragStartOffset = Vector2.zero;
                    if (onDragStarted != null)
                    {
                        onDragStarted();
                    }
                }
            }
            else if (centerOnChild)
            {
                centerOnChild.Recenter();
            }
            else
            {
                if (restrictWithinPanel && mPanel.clipping != UIDrawCall.Clipping.None)
                {
                    RestrictWithinBounds(dragEffect == DragEffect.None, canMoveHorizontally, canMoveVertically);
                }

                if (mDragStarted && onDragFinished != null)
                {
                    onDragFinished();
                }
                if (!mShouldMove && onStoppedMoving != null)
                {
                    onStoppedMoving();
                }
            }
        }
    }
예제 #23
0
    private IEnumerator MoveOn(GameObject goItem)
    {
        // 等待消失动画完成
        yield return(new WaitForSeconds(_aniTime));

        goItem.SendMessage("OnWrapDisappearEnd", SendMessageOptions.DontRequireReceiver);

        Vector3 disappearPos = goItem.transform.localPosition;
        // 移到最后或者最前
        Vector3 rightPos = GetRightestPos() + new Vector3(itemSize, 0f, 0f);

        // 可以移动到最右
        // 不需要取绝对值,横向滚动条物件的x值肯定大于等于0
        // 纵向的才要
        if (Mathf.RoundToInt(rightPos.x / itemSize) < totalSize)
        {
            goItem.transform.localPosition = rightPos;
            onUpdateItem(goItem.transform, Mathf.Abs(Mathf.RoundToInt(goItem.transform.localPosition.x / itemSize)));
        }
        else
        {
            Vector3 leftPos = GetLeftestPos() - new Vector3(itemSize, 0f, 0f);

            // 可以移动最左
            // 这里不能取绝对值。。 否则结果肯定大于等于0了
            if (Mathf.RoundToInt(leftPos.x / itemSize) >= 0)
            {
                goItem.transform.localPosition = leftPos;
                onUpdateItem(goItem.transform, Mathf.Abs(Mathf.RoundToInt(goItem.transform.localPosition.x / itemSize)));
            }
            else
            {
                // 两边都不满足,则移动到最右,并且隐藏
                goItem.transform.localPosition = rightPos;
                NGUITools.SetActive(goItem, false);
            }
        }

        // 如果总大小小于预留控件大小,则需要隐藏刚消失的控件
//         if (totalSize < mChildren.size)
//         {
//             NGUITools.SetActive(goItem, false);
//         }
//         else
//         {
//             onUpdateItem(goItem.transform, Mathf.Abs(Mathf.RoundToInt(goItem.transform.localPosition.x / itemSize)));
//         }

        bool hasSpring = false;

        // 超过消失点的控件,spring到合适位置
        // to do 如果是不可见的控件,不能用spring,直接设置到目标位置
        for (int i = 0; i < mChildren.size; ++i)
        {
            Transform t = mChildren[i];

            if (t.localPosition.x > disappearPos.x)
            {
                if (NGUITools.GetActive(t.gameObject))
                {
                    hasSpring = true;
                    if (Mathf.RoundToInt(t.localPosition.x - disappearPos.x) == itemSize)
                    {
                        t.gameObject.SendMessage("OnWrapSpringBegin", SendMessageOptions.DontRequireReceiver);
                        SpringPosition.Begin(t.gameObject, t.localPosition - new Vector3(itemSize, 0f, 0f), _aniSpringStrenth).onFinished = _onAniFinish;
                    }
                    else
                    {
                        SpringPosition.Begin(t.gameObject, t.localPosition - new Vector3(itemSize, 0f, 0f), _aniSpringStrenth);
                    }
                }
                else
                {
                    t.localPosition = t.localPosition - new Vector3(itemSize, 0f, 0f);
                }
            }
        }

        if (!hasSpring)
        {
            if (_onAniFinish != null)
            {
                _onAniFinish();
                _onAniFinish = null;
            }
        }
    }
    /// <summary>
    /// Drag the object along the plane.
    /// </summary>

    public void Drag()
    {
        if (UICamera.currentScheme == UICamera.ControlScheme.Controller)
        {
            return;
        }

        if (enabled && NGUITools.GetActive(gameObject) && mShouldMove)
        {
            if (mDragID == -10)
            {
                mDragID = UICamera.currentTouchID;
            }
            UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;

            // Prevents the drag "jump". Contributed by 'mixd' from the Tasharen forums.
            if (smoothDragStart && !mDragStarted)
            {
                mDragStarted     = true;
                mDragStartOffset = UICamera.currentTouch.totalDelta;
                if (onDragStarted != null)
                {
                    onDragStarted();
                }
            }

            Ray ray = smoothDragStart ?
                      UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos - mDragStartOffset) :
                      UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos);

            float dist = 0f;

            if (mPlane.Raycast(ray, out dist))
            {
                Vector3 currentPos = ray.GetPoint(dist);
                Vector3 offset     = currentPos - mLastPos;
                mLastPos = currentPos;

                if (offset.x != 0f || offset.y != 0f || offset.z != 0f)
                {
                    offset = mTrans.InverseTransformDirection(offset);

                    if (movement == Movement.Horizontal)
                    {
                        offset.y = 0f;
                        offset.z = 0f;
                    }
                    else if (movement == Movement.Vertical)
                    {
                        offset.x = 0f;
                        offset.z = 0f;
                    }
                    else if (movement == Movement.Unrestricted)
                    {
                        offset.z = 0f;
                    }
                    else
                    {
                        offset.Scale((Vector3)customMovement);
                    }
                    offset = mTrans.TransformDirection(offset);
                }

                // Adjust the momentum
                if (dragEffect == DragEffect.None)
                {
                    mMomentum = Vector3.zero;
                }
                else
                {
                    mMomentum = Vector3.Lerp(mMomentum, mMomentum + offset * (0.01f * momentumAmount), 0.67f);
                }

                // Move the scroll view
                if (!iOSDragEmulation || dragEffect != DragEffect.MomentumAndSpring)
                {
                    MoveAbsolute(offset);
                }
                else
                {
                    Vector3 constraint = mPanel.CalculateConstrainOffset(bounds.min, bounds.max);

                    if (constraint.magnitude > 1f)
                    {
                        MoveAbsolute(offset * 0.5f);
                        mMomentum *= 0.5f;
                    }
                    else
                    {
                        MoveAbsolute(offset);
                    }
                }

                // We want to constrain the UI to be within bounds
                if (restrictWithinPanel &&
                    mPanel.clipping != UIDrawCall.Clipping.None &&
                    dragEffect != DragEffect.MomentumAndSpring)
                {
                    RestrictWithinBounds(true, canMoveHorizontally, canMoveVertically);
                }
            }
        }
    }
예제 #25
0
    void OnKey(KeyCode key)
    {
        if (NGUITools.GetActive(this))
        {
            switch (key)
            {
            case KeyCode.LeftArrow:
                if (NGUITools.GetActive(selectOnLeft))
                {
                    UICamera.selectedObject = selectOnLeft.gameObject;
                }
                break;

            case KeyCode.RightArrow:
                if (NGUITools.GetActive(selectOnRight))
                {
                    UICamera.selectedObject = selectOnRight.gameObject;
                }
                break;

            case KeyCode.UpArrow:
                if (NGUITools.GetActive(selectOnUp))
                {
                    UICamera.selectedObject = selectOnUp.gameObject;
                }
                break;

            case KeyCode.DownArrow:
                if (NGUITools.GetActive(selectOnDown))
                {
                    UICamera.selectedObject = selectOnDown.gameObject;
                }
                break;

            case KeyCode.Tab:
                if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
                {
                    if (NGUITools.GetActive(selectOnLeft))
                    {
                        UICamera.selectedObject = selectOnLeft.gameObject;
                    }
                    else if (NGUITools.GetActive(selectOnUp))
                    {
                        UICamera.selectedObject = selectOnUp.gameObject;
                    }
                    else if (NGUITools.GetActive(selectOnDown))
                    {
                        UICamera.selectedObject = selectOnDown.gameObject;
                    }
                    else if (NGUITools.GetActive(selectOnRight))
                    {
                        UICamera.selectedObject = selectOnRight.gameObject;
                    }
                }
                else
                {
                    if (NGUITools.GetActive(selectOnRight))
                    {
                        UICamera.selectedObject = selectOnRight.gameObject;
                    }
                    else if (NGUITools.GetActive(selectOnDown))
                    {
                        UICamera.selectedObject = selectOnDown.gameObject;
                    }
                    else if (NGUITools.GetActive(selectOnUp))
                    {
                        UICamera.selectedObject = selectOnUp.gameObject;
                    }
                    else if (NGUITools.GetActive(selectOnLeft))
                    {
                        UICamera.selectedObject = selectOnLeft.gameObject;
                    }
                }
                break;
            }
        }
    }
예제 #26
0
 public void Press(bool pressed)
 {
     if (UICamera.currentScheme != UICamera.ControlScheme.Controller)
     {
         if (smoothDragStart && pressed)
         {
             mDragStarted     = false;
             mDragStartOffset = Vector2.zero;
         }
         if (base.enabled && NGUITools.GetActive(base.gameObject))
         {
             if (!pressed && mDragID == UICamera.currentTouchID)
             {
                 mDragID = -10;
             }
             mCalculatedBounds = false;
             mShouldMove       = shouldMove;
             if (mShouldMove)
             {
                 mPressed = pressed;
                 if (pressed)
                 {
                     mMomentum = Vector3.zero;
                     mScroll   = 0f;
                     DisableSpring();
                     mLastPos = UICamera.lastWorldPosition;
                     mPlane   = new Plane(mTrans.rotation * Vector3.back, mLastPos);
                     Vector2 clipOffset = mPanel.clipOffset;
                     clipOffset.x      = Mathf.Round(clipOffset.x);
                     clipOffset.y      = Mathf.Round(clipOffset.y);
                     mPanel.clipOffset = clipOffset;
                     Vector3 localPosition = mTrans.localPosition;
                     localPosition.x      = Mathf.Round(localPosition.x);
                     localPosition.y      = Mathf.Round(localPosition.y);
                     mTrans.localPosition = localPosition;
                     if (!smoothDragStart)
                     {
                         mDragStarted     = true;
                         mDragStartOffset = Vector2.zero;
                         if (onDragStarted != null)
                         {
                             onDragStarted();
                         }
                     }
                 }
                 else
                 {
                     if (restrictWithinPanel && mPanel.clipping != 0)
                     {
                         RestrictWithinBounds(dragEffect == DragEffect.None, canMoveHorizontally, canMoveVertically);
                     }
                     if (mDragStarted && onDragFinished != null)
                     {
                         onDragFinished();
                     }
                     if (!mShouldMove && onStoppedMoving != null)
                     {
                         onStoppedMoving();
                     }
                 }
             }
         }
     }
 }
예제 #27
0
    /// <summary>
    /// Returns the object under the specified position.
    /// </summary>

    static public bool Raycast(Vector3 inPos, ref RaycastHit hit)
    {
        for (int i = 0; i < mList.Count; ++i)
        {
            UICamera cam = mList[i];

            // Skip inactive scripts
            if (!cam.enabled || !NGUITools.GetActive(cam.gameObject))
            {
                continue;
            }

            // Convert to view space
            currentCamera = cam.cachedCamera;
            Vector3 pos = currentCamera.ScreenToViewportPoint(inPos);

            // If it's outside the camera's viewport, do nothing
            if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f)
            {
                continue;
            }

            // Cast a ray into the screen
            Ray ray = currentCamera.ScreenPointToRay(inPos);

            // Raycast into the screen
            int   mask = currentCamera.cullingMask & (int)cam.eventReceiverMask;
            float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane;

            // If raycasts should be clipped by panels, we need to find a panel for each hit
            if (cam.clipRaycasts)
            {
                RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask);

                if (hits.Length > 1)
                {
                    System.Array.Sort(hits, delegate(RaycastHit r1, RaycastHit r2) { return(r1.distance.CompareTo(r2.distance)); });

                    for (int b = 0, bmax = hits.Length; b < bmax; ++b)
                    {
                        if (IsVisible(ref hits[b]))
                        {
                            hit = hits[b];
                            return(true);
                        }
                    }
                }
                else if (hits.Length == 1 && IsVisible(ref hits[0]))
                {
                    hit = hits[0];
                    return(true);
                }
                continue;
            }
            if (Physics.Raycast(ray, out hit, dist, mask))
            {
                return(true);
            }
        }
        return(false);
    }
예제 #28
0
 public void Drag()
 {
     if (UICamera.currentScheme != UICamera.ControlScheme.Controller && base.enabled && NGUITools.GetActive(base.gameObject) && mShouldMove)
     {
         if (mDragID == -10)
         {
             mDragID = UICamera.currentTouchID;
         }
         UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;
         if (smoothDragStart && !mDragStarted)
         {
             mDragStarted     = true;
             mDragStartOffset = UICamera.currentTouch.totalDelta;
             if (onDragStarted != null)
             {
                 onDragStarted();
             }
         }
         Ray   ray   = (!smoothDragStart) ? UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos) : UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos - mDragStartOffset);
         float enter = 0f;
         if (mPlane.Raycast(ray, out enter))
         {
             Vector3 point  = ray.GetPoint(enter);
             Vector3 vector = point - mLastPos;
             mLastPos = point;
             if (vector.x != 0f || vector.y != 0f || vector.z != 0f)
             {
                 vector = mTrans.InverseTransformDirection(vector);
                 if (movement == Movement.Horizontal)
                 {
                     vector.y = 0f;
                     vector.z = 0f;
                 }
                 else if (movement == Movement.Vertical)
                 {
                     vector.x = 0f;
                     vector.z = 0f;
                 }
                 else if (movement == Movement.Unrestricted)
                 {
                     vector.z = 0f;
                 }
                 else
                 {
                     vector.Scale(customMovement);
                 }
                 vector = mTrans.TransformDirection(vector);
             }
             if (dragEffect == DragEffect.None)
             {
                 mMomentum = Vector3.zero;
             }
             else
             {
                 mMomentum = Vector3.Lerp(mMomentum, mMomentum + vector * (0.01f * momentumAmount), 0.67f);
             }
             if (!iOSDragEmulation || dragEffect != DragEffect.MomentumAndSpring)
             {
                 MoveAbsolute(vector);
             }
             else if (mPanel.CalculateConstrainOffset(bounds.min, bounds.max).magnitude > 1f)
             {
                 MoveAbsolute(vector * 0.5f);
                 mMomentum *= 0.5f;
             }
             else
             {
                 MoveAbsolute(vector);
             }
             if (restrictWithinPanel && mPanel.clipping != 0 && dragEffect != DragEffect.MomentumAndSpring)
             {
                 RestrictWithinBounds(/*instant:*/ true, canMoveHorizontally, canMoveVertically);
             }
         }
     }
 }
예제 #29
0
    /// <summary>
    /// Apply the dragging momentum.
    /// </summary>

    void LateUpdate()
    {
        if (!Application.isPlaying)
        {
            return;
        }
        float delta = RealTime.deltaTime;

        // Fade the scroll bars if needed
        if (showScrollBars != ShowCondition.Always && (verticalScrollBar || horizontalScrollBar))
        {
            bool vertical   = false;
            bool horizontal = false;

            if (showScrollBars != ShowCondition.WhenDragging || mDragID != -10 || mMomentum.magnitude > 0.01f)
            {
                vertical   = shouldMoveVertically;
                horizontal = shouldMoveHorizontally;
            }

            if (verticalScrollBar)
            {
                float alpha = verticalScrollBar.alpha;
                alpha += vertical ? delta * 6f : -delta * 3f;
                alpha  = Mathf.Clamp01(alpha);
                if (verticalScrollBar.alpha != alpha)
                {
                    verticalScrollBar.alpha = alpha;
                }
            }

            if (horizontalScrollBar)
            {
                float alpha = horizontalScrollBar.alpha;
                alpha += horizontal ? delta * 6f : -delta * 3f;
                alpha  = Mathf.Clamp01(alpha);
                if (horizontalScrollBar.alpha != alpha)
                {
                    horizontalScrollBar.alpha = alpha;
                }
            }
        }

        if (!mShouldMove)
        {
            return;
        }

        // Apply momentum
        if (!mPressed)
        {
            var momentumMagnitude = mMomentum.magnitude;
            if (mChangePressed)
            {
                if (momentumMagnitude <= stopMomentumValue)
                {
                    momentumMagnitude = 0;
                    mScroll           = 0f;
                    mMomentum         = Vector3.zero;

                    SpringPanel sp = GetComponent <SpringPanel>();
                    if (sp != null && sp.enabled)
                    {
                        return;
                    }

                    mShouldMove = false;
                    if (onStoppedMoving != null)
                    {
                        onStoppedMoving();
                    }
                }
                mChangePressed = false;
            }
            if (momentumMagnitude > 0.0001f || mScroll != 0f)
            {
                if (movement == Movement.Horizontal)
                {
                    mMomentum -= mTrans.TransformDirection(new Vector3(mScroll * 0.05f, 0f, 0f));
                }
                else if (movement == Movement.Vertical)
                {
                    mMomentum -= mTrans.TransformDirection(new Vector3(0f, mScroll * 0.05f, 0f));
                }
                else if (movement == Movement.Unrestricted)
                {
                    mMomentum -= mTrans.TransformDirection(new Vector3(mScroll * 0.05f, mScroll * 0.05f, 0f));
                }
                else
                {
                    mMomentum -= mTrans.TransformDirection(new Vector3(
                                                               mScroll * customMovement.x * 0.05f,
                                                               mScroll * customMovement.y * 0.05f, 0f));
                }
                mScroll = NGUIMath.SpringLerp(mScroll, 0f, 20f, delta);

                // Move the scroll view
                Vector3 offset = NGUIMath.SpringDampen(ref mMomentum, dampenStrength, delta * scrollSpeedReduce);
                MoveAbsolute(offset);

                // Restrict the contents to be within the scroll view's bounds
                if (restrictWithinPanel && mPanel.clipping != UIDrawCall.Clipping.None)
                {
                    if (NGUITools.GetActive(centerOnChild))
                    {
                        if (centerOnChild.nextPageThreshold != 0f)
                        {
                            mMomentum = Vector3.zero;
                            mScroll   = 0f;
                        }
                        else
                        {
                            centerOnChild.Recenter();
                        }
                    }
                    else
                    {
                        RestrictWithinBounds(false, canMoveHorizontally, canMoveVertically);
                    }
                }

                if (onMomentumMove != null)
                {
                    onMomentumMove();
                }
            }
            else
            {
                mScroll   = 0f;
                mMomentum = Vector3.zero;

                SpringPanel sp = GetComponent <SpringPanel>();
                if (sp != null && sp.enabled)
                {
                    return;
                }

                mShouldMove = false;
                if (onStoppedMoving != null)
                {
                    onStoppedMoving();
                }
            }
        }
        else
        {
            // Dampen the momentum
            mScroll = 0f;
            NGUIMath.SpringDampen(ref mMomentum, 9f, delta);
        }
    }
예제 #30
0
    /// <summary>
    /// Drag the object along the plane.
    /// </summary>

    public void Drag()
    {
        if (enabled && NGUITools.GetActive(gameObject) && mShouldMove)
        {
            if (mDragID == -10)
            {
                mDragID = NGUICamera.currentTouchID;
            }
            NGUICamera.currentTouch.clickNotification = NGUICamera.ClickNotification.BasedOnDelta;

            // Prevents the drag "jump". Contributed by 'mixd' from the Tasharen forums.
            if (smoothDragStart && !mDragStarted)
            {
                mDragStarted     = true;
                mDragStartOffset = NGUICamera.currentTouch.totalDelta;
            }

            Ray ray = smoothDragStart ?
                      NGUICamera.currentCamera.ScreenPointToRay(NGUICamera.currentTouch.pos - mDragStartOffset) :
                      NGUICamera.currentCamera.ScreenPointToRay(NGUICamera.currentTouch.pos);

            float dist = 0f;

            if (mPlane.Raycast(ray, out dist))
            {
                Vector3 currentPos = ray.GetPoint(dist);
                Vector3 offset     = currentPos - mLastPos;
                mLastPos = currentPos;

                if (offset.x != 0f || offset.y != 0f)
                {
                    offset = mTrans.InverseTransformDirection(offset);
                    offset.Scale(scale);
                    offset = mTrans.TransformDirection(offset);
                }

                // Adjust the momentum
                mMomentum = Vector3.Lerp(mMomentum, mMomentum + offset * (0.01f * momentumAmount), 0.67f);

                // Move the panel
                if (!iOSDragEmulation)
                {
                    MoveAbsolute(offset);
                }
                else
                {
                    Vector3 constraint = mPanel.CalculateConstrainOffset(bounds.min, bounds.max);

                    if (constraint.magnitude > 0.001f)
                    {
                        MoveAbsolute(offset * 0.5f);
                        mMomentum *= 0.5f;
                    }
                    else
                    {
                        MoveAbsolute(offset);
                    }
                }

                // We want to constrain the UI to be within bounds
                if (restrictWithinPanel &&
                    mPanel.clipping != NGUIDrawCall.Clipping.None &&
                    dragEffect != DragEffect.MomentumAndSpring)
                {
                    RestrictWithinBounds(true);
                }
            }
        }
    }