Ejemplo n.º 1
0
	static void Load ()
	{
		mLoaded			= true;
		mPartial		= EditorPrefs.GetString("NGUI Partial");
		mFontName		= EditorPrefs.GetString("NGUI Font Name");
		mAtlasName		= EditorPrefs.GetString("NGUI Atlas Name");
		mFontData		= GetObject("NGUI Font Asset") as TextAsset;
		mFontTexture	= GetObject("NGUI Font Texture") as Texture2D;
		mFont			= GetObject("NGUI Font") as UIFont;
		mAtlas			= GetObject("NGUI Atlas") as UIAtlas;
		mAtlasPadding	= EditorPrefs.GetInt("NGUI Atlas Padding", 1);
		mAtlasTrimming	= EditorPrefs.GetBool("NGUI Atlas Trimming", true);
		mAtlasPMA		= EditorPrefs.GetBool("NGUI Atlas PMA", true);
		mUnityPacking	= EditorPrefs.GetBool("NGUI Unity Packing", true);
		mForceSquare	= EditorPrefs.GetBool("NGUI Force Square Atlas", true);
		mPivot			= (UIWidget.Pivot)EditorPrefs.GetInt("NGUI Pivot", (int)mPivot);
		mLayer			= EditorPrefs.GetInt("NGUI Layer", -1);
		mDynFont		= GetObject("NGUI DynFont") as Font;
		mDynFontSize	= EditorPrefs.GetInt("NGUI DynFontSize", 16);
		mDynFontStyle	= (FontStyle)EditorPrefs.GetInt("NGUI DynFontStyle", (int)FontStyle.Normal);

		if (mLayer < 0 || string.IsNullOrEmpty(LayerMask.LayerToName(mLayer))) mLayer = -1;

		if (mLayer == -1) mLayer = LayerMask.NameToLayer("UI");
		if (mLayer == -1) mLayer = LayerMask.NameToLayer("GUI");
		if (mLayer == -1) mLayer = 5;

		EditorPrefs.SetInt("UI Layer", mLayer);

		LoadColor();
	}
Ejemplo n.º 2
0
 protected void Init()
 {
     if (this.mDoInit && (this.label != null))
     {
         this.mDoInit = false;
         this.mDefaultText = this.label.text;
         this.mDefaultColor = this.label.color;
         this.label.supportEncoding = false;
         this.mPivot = this.label.pivot;
         this.mPosition = this.label.cachedTransform.localPosition.x;
         this.UpdateLabel();
     }
 }
Ejemplo n.º 3
0
	static void Load ()
	{
		mLoaded			= true;
		mPartial		= EditorPrefs.GetString("NGUI Partial");
		mFontName		= EditorPrefs.GetString("NGUI Font Name");
		mAtlasName		= EditorPrefs.GetString("NGUI Atlas Name");
		mFontData		= GetObject("NGUI Font Asset") as TextAsset;
		mFontTexture	= GetObject("NGUI Font Texture") as Texture2D;
		mFont			= GetObject("NGUI Font") as UIFont;
		mAtlas			= GetObject("NGUI Atlas") as UIAtlas;
		mAtlasPadding	= EditorPrefs.GetInt("NGUI Atlas Padding", 1);
		mAtlasTrimming	= EditorPrefs.GetBool("NGUI Atlas Trimming", true);
		mUnityPacking	= EditorPrefs.GetBool("NGUI Unity Packing", true);
		mPivot			= (UIWidget.Pivot)EditorPrefs.GetInt("NGUI Pivot", (int)mPivot);
	}
Ejemplo n.º 4
0
	static void Load ()
	{
		int l = LayerMask.NameToLayer("HotUI");//UI->HotUI Jerrylai_2014-12-11 13:13:24
		if (l == -1) l = LayerMask.NameToLayer("GUI");

		mLoaded			= true;
		mPartial		= EditorPrefs.GetString("NGUI Partial");
		mFontName		= EditorPrefs.GetString("NGUI Font Name");
		mAtlasName		= EditorPrefs.GetString("NGUI Atlas Name");
		mFontData		= GetObject("NGUI Font Asset") as TextAsset;
		mFontTexture	= GetObject("NGUI Font Texture") as Texture2D;
		mFont			= GetObject("NGUI Font") as UIFont;
		mAtlas			= GetObject("NGUI Atlas") as UIAtlas;
		mAtlasPadding	= EditorPrefs.GetInt("NGUI Atlas Padding", 1);
		mAtlasTrimming	= EditorPrefs.GetBool("NGUI Atlas Trimming", true);
		mUnityPacking	= EditorPrefs.GetBool("NGUI Unity Packing", true);
		mForceSquare	= EditorPrefs.GetBool("NGUI Force Square Atlas", true);
		mPivot			= (UIWidget.Pivot)EditorPrefs.GetInt("NGUI Pivot", (int)mPivot);
		mLayer			= EditorPrefs.GetInt("NGUI Layer", l);

		LoadColor();
	}
Ejemplo n.º 5
0
 public static void ResizeWidget(UIWidget w, UIWidget.Pivot pivot, float x, float y, int minWidth, int minHeight)
 {
     ResizeWidget(w, pivot, x, y, 2, 2, 100000, 100000);
 }
Ejemplo n.º 6
0
    /// <summary>
    /// Adjust the panel's position and clipping rectangle.
    /// </summary>

    void AdjustClipping(UIPanel p, Vector3 startLocalPos, Vector4 startCR, Vector3 worldDelta, UIWidget.Pivot pivot)
    {
        Transform  t             = p.cachedTransform;
        Transform  parent        = t.parent;
        Matrix4x4  parentToLocal = (parent != null) ? t.parent.worldToLocalMatrix : Matrix4x4.identity;
        Matrix4x4  worldToLocal  = parentToLocal;
        Quaternion invRot        = Quaternion.Inverse(t.localRotation);

        worldToLocal = worldToLocal * Matrix4x4.TRS(Vector3.zero, invRot, Vector3.one);
        Vector3 localDelta = worldToLocal.MultiplyVector(worldDelta);

        float left   = 0f;
        float right  = 0f;
        float top    = 0f;
        float bottom = 0f;

        Vector2 dragPivot = NGUIMath.GetPivotOffset(pivot);

        if (dragPivot.x == 0f && dragPivot.y == 1f)
        {
            left = localDelta.x;
            top  = localDelta.y;
        }
        else if (dragPivot.x == 0f && dragPivot.y == 0.5f)
        {
            left = localDelta.x;
        }
        else if (dragPivot.x == 0f && dragPivot.y == 0f)
        {
            left   = localDelta.x;
            bottom = localDelta.y;
        }
        else if (dragPivot.x == 0.5f && dragPivot.y == 1f)
        {
            top = localDelta.y;
        }
        else if (dragPivot.x == 0.5f && dragPivot.y == 0f)
        {
            bottom = localDelta.y;
        }
        else if (dragPivot.x == 1f && dragPivot.y == 1f)
        {
            right = localDelta.x;
            top   = localDelta.y;
        }
        else if (dragPivot.x == 1f && dragPivot.y == 0.5f)
        {
            right = localDelta.x;
        }
        else if (dragPivot.x == 1f && dragPivot.y == 0f)
        {
            right  = localDelta.x;
            bottom = localDelta.y;
        }

        AdjustClipping(p, startCR,
                       Mathf.RoundToInt(left),
                       Mathf.RoundToInt(top),
                       Mathf.RoundToInt(right),
                       Mathf.RoundToInt(bottom));
    }
Ejemplo n.º 7
0
    protected void SlicedFill(BetterList <Vector3> verts, BetterList <Vector2> uvs, BetterList <Color32> cols)
    {
        if (this.mOuterUV == this.mInnerUV)
        {
            this.SimpleFill(verts, uvs, cols);
            return;
        }
        Vector2[] array       = new Vector2[4];
        Vector2[] array2      = new Vector2[4];
        Texture   mainTexture = this.mainTexture;

        array[0] = Vectors.v2zero;
        array[1] = Vectors.v2zero;
        array[2] = new Vector2(1f, -1f);
        array[3] = new Vector2(1f, -1f);
        if (mainTexture != null)
        {
            float   pixelSize  = this.atlas.pixelSize;
            float   num        = (this.mInnerUV.xMin - this.mOuterUV.xMin) * pixelSize;
            float   num2       = (this.mOuterUV.xMax - this.mInnerUV.xMax) * pixelSize;
            float   num3       = (this.mInnerUV.yMax - this.mOuterUV.yMax) * pixelSize;
            float   num4       = (this.mOuterUV.yMin - this.mInnerUV.yMin) * pixelSize;
            Vector3 localScale = base.cachedTransform.localScale;
            localScale.x = Mathf.Max(0f, localScale.x);
            localScale.y = Mathf.Max(0f, localScale.y);
            Vector2        vector  = new Vector2(localScale.x / (float)mainTexture.width, localScale.y / (float)mainTexture.height);
            Vector2        vector2 = new Vector2(num / vector.x, num3 / vector.y);
            Vector2        vector3 = new Vector2(num2 / vector.x, num4 / vector.y);
            UIWidget.Pivot pivot   = base.pivot;
            if (pivot == UIWidget.Pivot.Right || pivot == UIWidget.Pivot.TopRight || pivot == UIWidget.Pivot.BottomRight)
            {
                array[0].x = Mathf.Min(0f, 1f - (vector3.x + vector2.x));
                array[1].x = array[0].x + vector2.x;
                array[2].x = array[0].x + Mathf.Max(vector2.x, 1f - vector3.x);
                array[3].x = array[0].x + Mathf.Max(vector2.x + vector3.x, 1f);
            }
            else
            {
                array[1].x = vector2.x;
                array[2].x = Mathf.Max(vector2.x, 1f - vector3.x);
                array[3].x = Mathf.Max(vector2.x + vector3.x, 1f);
            }
            if (pivot == UIWidget.Pivot.Bottom || pivot == UIWidget.Pivot.BottomLeft || pivot == UIWidget.Pivot.BottomRight)
            {
                array[0].y = Mathf.Max(0f, -1f - (vector3.y + vector2.y));
                array[1].y = array[0].y + vector2.y;
                array[2].y = array[0].y + Mathf.Min(vector2.y, -1f - vector3.y);
                array[3].y = array[0].y + Mathf.Min(vector2.y + vector3.y, -1f);
            }
            else
            {
                array[1].y = vector2.y;
                array[2].y = Mathf.Min(vector2.y, -1f - vector3.y);
                array[3].y = Mathf.Min(vector2.y + vector3.y, -1f);
            }
            array2[0] = new Vector2(this.mOuterUV.xMin, this.mOuterUV.yMax);
            array2[1] = new Vector2(this.mInnerUV.xMin, this.mInnerUV.yMax);
            array2[2] = new Vector2(this.mInnerUV.xMax, this.mInnerUV.yMin);
            array2[3] = new Vector2(this.mOuterUV.xMax, this.mOuterUV.yMin);
        }
        else
        {
            for (int i = 0; i < 4; i++)
            {
                array2[i] = Vectors.v2zero;
            }
        }
        Color color = base.color;

        color.a *= this.mPanel.alpha;
        Color32 item = (!this.atlas.premultipliedAlpha) ? color : NGUITools.ApplyPMA(color);

        for (int j = 0; j < 3; j++)
        {
            int num5 = j + 1;
            for (int k = 0; k < 3; k++)
            {
                if (this.mFillCenter || j != 1 || k != 1)
                {
                    int num6 = k + 1;
                    verts.Add(new Vector3(array[num5].x, array[k].y, 0f));
                    verts.Add(new Vector3(array[num5].x, array[num6].y, 0f));
                    verts.Add(new Vector3(array[j].x, array[num6].y, 0f));
                    verts.Add(new Vector3(array[j].x, array[k].y, 0f));
                    uvs.Add(new Vector2(array2[num5].x, array2[k].y));
                    uvs.Add(new Vector2(array2[num5].x, array2[num6].y));
                    uvs.Add(new Vector2(array2[j].x, array2[num6].y));
                    uvs.Add(new Vector2(array2[j].x, array2[k].y));
                    cols.Add(item);
                    cols.Add(item);
                    cols.Add(item);
                    cols.Add(item);
                }
            }
        }
    }
Ejemplo n.º 8
0
        public static void SetCursorToWindowResizer(UIWidget.Pivot pivot)
        {
            var texture = GetCursorTextureFromWindowResizePivot(pivot);

            SetCursorTexture(texture);
        }
Ejemplo n.º 9
0
    public virtual void Awake()
    {
        if (CoverFlow) {
            if(_CoverFlowCount!=0){
                CoverFlowCount =_CoverFlowCount;
            }
            if(transform.childCount<CoverFlowCount+1||Alwaysreset){

                int count = transform.childCount;
                for(int i = 0; i<count;i++){
                    DestroyImmediate(transform.GetChild(0).gameObject);
                }
                if(transform.parent.FindChild("Benchmark")==null){
                    GameObject Benchmark = Instantiate<GameObject>(Resources.Load ("Benchmark") as GameObject);
                    Benchmark.transform.name = "Benchmark";
                    Benchmark.transform.parent = transform.parent;
                    Benchmark.transform.localScale = new Vector3(1,1,1);
                    Benchmark.transform.localPosition = transform.localPosition;

                }
                if(transform.FindChild("BG")==null){
                    GameObject Front =  Instantiate<GameObject>(Resources.Load ("BG") as GameObject);
                    Front.transform.name = "BG";
                    Front.transform.parent = transform;
                    Front.transform.localScale = new Vector3(1,1,1);
                }
                BenchmarkSize = 720f;
                if(CoverFlowCount>4){
                    if(CoverFlowCount == 5){
                        BenchmarkSize = 800f;
                    }else{
                        BenchmarkSize = 800f + (((float)CoverFlowCount-5f)*220f);
                    }
                }

                transform.FindChild("BG").localPosition = new Vector3((Size.x*(CoverFlowCount-1))*0.5f,((MaxSize.y-200)*0.5f)+20f);
                transform.FindChild("BG").GetComponent<BoxCollider2D>().size = new Vector2((Size.x*CoverFlowCount)+((360-(Size.x*0.5f))*2f),MaxSize.y);
                transform.FindChild("BG").GetComponent<BoxCollider2D>().offset = new Vector2(0,0);
                transform.FindChild("BG").GetComponent<UITexture>().SetRect((Size.x*CoverFlowCount)+((360-(Size.x*0.5f))*2f),MaxSize.y);

                transform.parent.FindChild("Benchmark").GetComponent<BoxCollider2D>().size = new Vector2(BenchmarkSize,Size.y);
                transform.parent.FindChild("Benchmark").GetComponent<CoverFlowOndrag>().BenchmarkSize = BenchmarkSize;
                transform.parent.FindChild("Benchmark").GetComponent<CoverFlowOndrag>().DefaultSize = DefaultSize;
                transform.parent.FindChild("Benchmark").GetComponent<CoverFlowOndrag>().MaxSize = MaxSize;
                transform.parent.FindChild("Benchmark").GetComponent<CoverFlowOndrag>().Size = Size;
                transform.parent.FindChild("Benchmark").GetComponent<CoverFlowOndrag>().Gap = Gap;
                for(int i = 0; i<CoverFlowCount;i++){
                    //Debug.Log(CoverFlowCount);
                    GameObject Temp = (GameObject)Instantiate(CoverFlowItem);
                    Temp.transform.FindChild("CoverFlowItem").tag = "item";
                    Temp.transform.name = "Item " + i.ToString();
                    Temp.transform.parent = transform;
                    Temp.transform.localScale = new Vector3(1,1,1);
                    Temp.transform.localPosition = new Vector3(Size.x*i,((MaxSize.y-200)*0.5f)+20f);
                    Temp.transform.FindChild("CoverFlowItem").GetComponent<UITexture>().SetRect(DefaultSize.x,DefaultSize.y);

                    if(Temp.transform.FindChild("CoverFlowItem").GetComponent<UIDragScrollView>()==null){
                        Temp.transform.FindChild("CoverFlowItem").gameObject.AddComponent<UIDragScrollView>();
                    }
                    if(Temp.transform.FindChild("CoverFlowItem").GetComponent<BoxCollider2D>()==null){
                        Temp.transform.FindChild("CoverFlowItem").gameObject.AddComponent<BoxCollider2D>();
                    }
                    Temp.transform.FindChild("CoverFlowItem").GetComponent<BoxCollider2D>().size = DefaultSize;
                    Temp.transform.FindChild("CoverFlowItem").GetComponent<UITexture>().SetRect(DefaultSize.x,DefaultSize.y);
                    Temp.transform.GetComponent<UIPanel>().SetRect(DefaultSize.x,DefaultSize.y);
                    Temp.transform.FindChild("CoverFlowItem").FindChild("BG").GetComponent<UISprite>().SetRect(DefaultSize.x,DefaultSize.y);
                    if(i>=CoverFlowCount-(int)Mathf.Round((float)(CoverFlowCount-3)*0.5f)){
                        int num = CoverFlowCount-(int)Mathf.Round((float)(CoverFlowCount-3)*0.5f);

                            Temp.transform.name = "Item " + (num-(i+1)).ToString();
                            Temp.transform.localPosition = new Vector3(Size.x*(num-(i+1)),((MaxSize.y-200)*0.5f)+20f);

                    }
                }
            }

        }

        mTrans = transform;
        mPanel = GetComponent<UIPanel>();

        if (mPanel.clipping == UIDrawCall.Clipping.None)
            mPanel.clipping = UIDrawCall.Clipping.ConstrainButDontClip;

        // Auto-upgrade
        if (movement != Movement.Custom && scale.sqrMagnitude > 0.001f)
        {
            if (scale.x == 1f && scale.y == 0f)
            {
                movement = Movement.Horizontal;
            }
            else if (scale.x == 0f && scale.y == 1f)
            {
                movement = Movement.Vertical;
            }
            else if (scale.x == 1f && scale.y == 1f)
            {
                movement = Movement.Unrestricted;
            }
            else
            {
                movement = Movement.Custom;
                customMovement.x = scale.x;
                customMovement.y = scale.y;
            }
            scale = Vector3.zero;
        #if UNITY_EDITOR
            NGUITools.SetDirty(this);
        #endif
        }

        // Auto-upgrade
        if (contentPivot == UIWidget.Pivot.TopLeft && relativePositionOnReset != Vector2.zero)
        {
            contentPivot = NGUIMath.GetPivot(new Vector2(relativePositionOnReset.x, 1f - relativePositionOnReset.y));
            relativePositionOnReset = Vector2.zero;
        #if UNITY_EDITOR
            NGUITools.SetDirty(this);
        #endif
        }
    }
Ejemplo n.º 10
0
 protected void Init()
 {
     if (this.mDoInit && this.label != null)
     {
         this.mDoInit = false;
         this.mDefaultText = this.label.text;
         this.mDefaultColor = this.label.color;
         this.label.supportEncoding = false;
         if (this.label.alignment == NGUIText.Alignment.Justified)
         {
             this.label.alignment = NGUIText.Alignment.Left;
             global::Debug.LogWarning(new object[]
             {
                 "Input fields using labels with justified alignment are not supported at this time",
                 this
             });
         }
         this.mPivot = this.label.pivot;
         this.mPosition = this.label.cachedTransform.localPosition.x;
         this.UpdateLabel();
     }
 }
Ejemplo n.º 11
0
 static bool IsRight(UIWidget.Pivot pivot)
 {
     return(pivot == UIWidget.Pivot.Right ||
            pivot == UIWidget.Pivot.TopRight ||
            pivot == UIWidget.Pivot.BottomRight);
 }
Ejemplo n.º 12
0
 public static void ResizeWidget(UIWidget w, UIWidget.Pivot pivot, Single x, Single y, Int32 minWidth, Int32 minHeight)
 {
     NGUIMath.ResizeWidget(w, pivot, x, y, 2, 2, 100000, 100000);
 }
Ejemplo n.º 13
0
    public bool SetWidthDelta(int scale, float delta)
    {
        bool res = false;

        if (IsLock)
        {
        }
        else
        {
            UIWidget w = GetWidget();
            if (w != null)
            {
                UIWidget.Pivot lastPivot = w.pivot;
                w.pivot = UIWidget.Pivot.Left;

                int new_width = GetRealWidth(GetParentUI(), w, scale, delta);
                if (new_width != w.width)
                {
                    res = true;
                    if (scale < 0)
                    {
                        w.pivot = UIWidget.Pivot.Right;
                        //Move(new Vector3(w.width - new_width, 0));
                    }
                    //NGUIMath.AdjustWidget(w, 0f, 0f, new_width - w.width, 0f);
                    w.width = new_width;
                    //Vector3 vBL = w.worldCorners[0];
                    //Vector3 vPos = w.transform.localPosition;
                }
                w.pivot = lastPivot;
            }
            else
            {
                BoxCollider box = GetComponent <BoxCollider>();
                if (box != null)
                {
                    float fMove = delta;
                    if (scale != 0 && Mathf.Abs(fMove) > float.Epsilon)
                    {
                        Vector3 center = box.center;
                        center.x  += fMove / 2;
                        box.center = center;

                        Vector3 size = box.size;
                        if (scale < 0)
                        {
                            size.x -= fMove;
                        }
                        else
                        {
                            size.x += fMove;
                        }
                        box.size = size;

                        res = true;
                    }
                }
            }
        }
        return(res);
    }
Ejemplo n.º 14
0
    private void HandleInput(Layout cur_layout)
    {
        Event e = Event.current;

        switch (e.type)
        {
        case EventType.MouseDown:
            if (m_view.ViewRect.Contains(e.mousePosition))
            {
                m_lastMousePos = m_view.GUIToWorld(new Vector3(e.mousePosition.x, e.mousePosition.y));
                if (e.button == 0)     // ×ó¼ü
                {
                    m_drag = true;

                    if (m_knob_sel_res.m_knob_index != -1)
                    {
                        m_knob_move = true;
                    }
                    else
                    {
                        UIElement sel_widget = cur_layout.RayTest(m_lastMousePos);

                        BeginSelChange(cur_layout);
                        if (sel_widget != null)
                        {
                            if (!cur_layout.IsElementSelected(sel_widget))
                            {
                                if (!e.control)
                                {
                                    cur_layout.ClearSel();
                                }
                                cur_layout.SelElement(sel_widget);
                            }
                            else
                            {
                                m_last_sel = sel_widget;
                            }
                        }
                        else
                        {
                            if (!e.control)
                            {
                                cur_layout.ClearSel();
                            }
                            m_draggingMousePos = m_lastMousePos;
                            BuildSelRect(m_pre_sel_rec, m_draggingMousePos, m_lastMousePos);
                            m_bound_selecting = true;
                        }
                        EndSelChange(cur_layout);
                        BeginSelChange(cur_layout);
                    }
                }
                else if (e.button == 2)     // Öмü
                {
                    m_camera_move = true;
                }
            }
            break;

        case EventType.MouseUp:
            if (m_last_sel != null && !m_sel_move)
            {
                if (e.control)
                {
                    cur_layout.UnSelElement(m_last_sel);
                }
                else
                {
                    cur_layout.ClearSel();
                    cur_layout.SelElement(m_last_sel);
                }
            }

            if (m_drag)
            {
                if (!m_knob_move)
                {
                    EndSelChange(cur_layout);
                }
                if (!m_bound_selecting && m_sel_move)
                {
                    CmdManager.Instance.EndCmd();
                }
            }

            m_drag            = false;
            m_camera_move     = false;
            m_bound_selecting = false;
            m_knob_move       = false;
            m_sel_move        = false;
            m_last_sel        = null;
            SelKnob(cur_layout, e.mousePosition);
            break;

        case EventType.ScrollWheel:
            if (m_view.ViewRect.Contains(e.mousePosition))
            {
                m_view.ScaleCamera(e.delta.y > 0);
            }
            break;

        case EventType.KeyDown:
            if (e.keyCode == KeyCode.UpArrow || e.keyCode == KeyCode.DownArrow || e.keyCode == KeyCode.LeftArrow || e.keyCode == KeyCode.RightArrow)
            {
                List <UIElement> sel_list = cur_layout.GetMoveUIs();

                if (sel_list.Count > 0 && EditorGUIUtility.keyboardControl == 0)
                {
                    Vector3 move_delta = new Vector3((e.keyCode == KeyCode.LeftArrow ? -1 : (e.keyCode == KeyCode.RightArrow ? 1 : 0)), (e.keyCode == KeyCode.UpArrow ? 1 : (e.keyCode == KeyCode.DownArrow ? -1 : 0)), 0);

                    CmdManager.Instance.BeginCmd(sel_list, "Move Widgets");
                    for (int i = 0; i < sel_list.Count; ++i)
                    {
                        if (sel_list[i].IsEditBoxCollider())
                        {
                            if (m_view.ShowBoxCollider)
                            {
                                sel_list[i].Move(move_delta);
                            }
                        }
                        else
                        {
                            sel_list[i].Move(move_delta);
                        }
                    }

                    //for (int i = 0; i < sel_list.Count; ++i)
                    //{
                    //    sel_list[i].SyncPrefabUI((int)EUIOpFlag.UOF_Shape);
                    //}
                    CmdManager.Instance.EndCmd();
                    LayoutEditorWindow.RequestRepaint();

                    cur_layout.SetDirty();
                }
            }
            break;

        case EventType.MouseMove:
        case EventType.MouseDrag:
            Vector3 curMousePos = m_view.GUIToWorld(new Vector3(e.mousePosition.x, e.mousePosition.y));

            if (m_camera_move)
            {
                Vector3 camera_move_delta = m_lastMousePos - curMousePos;

                m_view.MoveCamera(camera_move_delta.x, camera_move_delta.y);
                m_lastMousePos = m_view.GUIToWorld(new Vector3(e.mousePosition.x, e.mousePosition.y));
            }
            else if (m_drag)           // Êó±ê×ó¼ü±»°´ÏÂ
            {
                if (m_bound_selecting) // ¿òÑ¡
                {
                    BuildSelRect(m_cur_sel_rect, m_draggingMousePos, curMousePos);

                    List <UIElement> widgets = cur_layout.GetAllUIs(false);

                    for (int i = 0; i < widgets.Count; ++i)
                    {
                        UIElement w           = widgets[i];
                        Vector3[] corners     = w.worldCorners;
                        bool      in_pre_rect = SelUI(corners, m_pre_sel_rec);
                        bool      in_cur_rect = SelUI(corners, m_cur_sel_rect);

                        if (in_pre_rect != in_cur_rect)
                        {
                            if (in_cur_rect)
                            {
                                if (!cur_layout.IsElementSelected(w))
                                {
                                    cur_layout.SelElement(w);
                                }
                                else if (e.control)
                                {
                                    cur_layout.UnSelElement(w);
                                }
                            }
                            else
                            {
                                if (cur_layout.IsElementSelected(w))
                                {
                                    cur_layout.UnSelElement(w);
                                }
                                else if (e.control)
                                {
                                    cur_layout.SelElement(w);
                                }
                            }
                        }
                    }
                    BuildSelRect(m_pre_sel_rec, m_draggingMousePos, curMousePos);
                    m_lastMousePos = curMousePos;
                }
                else
                {
                    bool             real_move  = false;
                    Vector3          move_delta = curMousePos - m_lastMousePos;
                    List <UIElement> sel_list   = cur_layout.GetMoveUIs();

                    if (!m_sel_move)
                    {
                        CmdManager.Instance.BeginCmd(sel_list, (m_knob_move ? "Resize Widgets" : "Move Widgets"));
                    }
                    if (m_knob_move)
                    {
                        UIWidget.Pivot pivot   = GetKnobPivot();
                        int            x_scale = GetKnobXScale(pivot);
                        int            y_scale = GetKnobYScale(pivot);

                        for (int i = 0; i < sel_list.Count; ++i)
                        {
                            UIElement ui_element = sel_list[i];

                            if (ui_element.IsEditBoxCollider() && !m_view.ShowBoxCollider)
                            {
                                continue;
                            }

                            if (ui_element.SetWidthDelta(x_scale, move_delta.x))
                            {
                                real_move = true;
                            }
                            if (ui_element.SetHeightDelta(y_scale, move_delta.y))
                            {
                                real_move = true;
                            }
                        }

                        //for (int i = 0; i < sel_list.Count; ++i)
                        //{
                        //    UIElement ui_element = sel_list[i];

                        //    if (ui_element.IsEditBoxCollider() && !m_view.ShowBoxCollider)
                        //        continue;

                        //    ui_element.SyncPrefabUI((int)EUIOpFlag.UOF_Shape);
                        //}
                    }
                    else
                    {
                        for (int i = 0; i < sel_list.Count; ++i)
                        {
                            // ÍÏקÒƶ¯
                            if (sel_list[i].IsEditBoxCollider())
                            {
                                if (m_view.ShowBoxCollider)
                                {
                                    sel_list[i].Move(move_delta);
                                }
                            }
                            else
                            {
                                sel_list[i].Move(move_delta);
                            }
                            real_move = true;
                        }

                        //for (int i = 0; i < sel_list.Count; ++i)
                        //{
                        //    sel_list[i].SyncPrefabUI((int)EUIOpFlag.UOF_Shape);
                        //}
                    }
                    m_sel_move = true;
                    if (real_move)
                    {
                        m_lastMousePos = curMousePos;
                    }

                    cur_layout.SetDirty();
                }
            }
            else
            {
                SelKnob(cur_layout, e.mousePosition);
            }
            break;
        }
        cur_layout.ResetAllUIElementOpFlag();
    }
Ejemplo n.º 15
0
 private void Awake()
 {
     this.mTrans = base.transform;
     this.mPanel = base.GetComponent<UIPanel>();
     if (this.mPanel.clipping == UIDrawCall.Clipping.None)
     {
         this.mPanel.clipping = UIDrawCall.Clipping.ConstrainButDontClip;
     }
     if (this.movement != UIScrollView.Movement.Custom && this.scale.sqrMagnitude > 0.001f)
     {
         if (this.scale.x == 1f && this.scale.y == 0f)
         {
             this.movement = UIScrollView.Movement.Horizontal;
         }
         else if (this.scale.x == 0f && this.scale.y == 1f)
         {
             this.movement = UIScrollView.Movement.Vertical;
         }
         else if (this.scale.x == 1f && this.scale.y == 1f)
         {
             this.movement = UIScrollView.Movement.Unrestricted;
         }
         else
         {
             this.movement = UIScrollView.Movement.Custom;
             this.customMovement.x = this.scale.x;
             this.customMovement.y = this.scale.y;
         }
         this.scale = Vector3.zero;
     }
     if (this.contentPivot == UIWidget.Pivot.TopLeft && this.relativePositionOnReset != Vector2.zero)
     {
         this.contentPivot = NGUIMath.GetPivot(new Vector2(this.relativePositionOnReset.x, 1f - this.relativePositionOnReset.y));
         this.relativePositionOnReset = Vector2.zero;
     }
 }
    public void UpdateNGUIText()
    {
        Font trueTypeFont = this.trueTypeFont;
        bool flag         = trueTypeFont != null;

        NGUIText.fontSize       = this.mPrintedSize;
        NGUIText.fontStyle      = this.mFontStyle;
        NGUIText.rectWidth      = this.mWidth;
        NGUIText.rectHeight     = this.mHeight;
        NGUIText.regionWidth    = Mathf.RoundToInt((float)this.mWidth * (this.mDrawRegion.z - this.mDrawRegion.x));
        NGUIText.regionHeight   = Mathf.RoundToInt((float)this.mHeight * (this.mDrawRegion.w - this.mDrawRegion.y));
        NGUIText.gradient       = (this.mApplyGradient && (this.mFont == null || !this.mFont.packedFontShader));
        NGUIText.gradientTop    = this.mGradientTop;
        NGUIText.gradientBottom = this.mGradientBottom;
        NGUIText.encoding       = this.mEncoding;
        NGUIText.premultiply    = this.mPremultiply;
        NGUIText.symbolStyle    = this.mSymbols;
        NGUIText.maxLines       = this.mMaxLineCount;
        NGUIText.spacingX       = this.effectiveSpacingX;
        NGUIText.spacingY       = this.effectiveSpacingY;
        NGUIText.fontScale      = ((!flag) ? ((float)this.mFontSize / (float)this.mFont.defaultSize * this.mScale) : this.mScale);
        if (this.mFont != null)
        {
            NGUIText.bitmapFont = this.mFont;
            while (true)
            {
                UIFont replacement = NGUIText.bitmapFont.replacement;
                if (replacement == null)
                {
                    break;
                }
                NGUIText.bitmapFont = replacement;
            }
            if (NGUIText.bitmapFont.isDynamic)
            {
                NGUIText.dynamicFont = NGUIText.bitmapFont.dynamicFont;
                NGUIText.bitmapFont  = null;
            }
            else
            {
                NGUIText.dynamicFont = null;
            }
        }
        else
        {
            NGUIText.dynamicFont = trueTypeFont;
            NGUIText.bitmapFont  = null;
        }
        if (flag && this.keepCrisp)
        {
            UIRoot root = base.root;
            if (root != null)
            {
                NGUIText.pixelDensity = ((!(root != null)) ? 1f : root.pixelSizeAdjustment);
            }
        }
        else
        {
            NGUIText.pixelDensity = 1f;
        }
        if (this.mDensity != NGUIText.pixelDensity)
        {
            this.ProcessText(false, false);
            NGUIText.rectWidth    = this.mWidth;
            NGUIText.rectHeight   = this.mHeight;
            NGUIText.regionWidth  = Mathf.RoundToInt((float)this.mWidth * (this.mDrawRegion.z - this.mDrawRegion.x));
            NGUIText.regionHeight = Mathf.RoundToInt((float)this.mHeight * (this.mDrawRegion.w - this.mDrawRegion.y));
        }
        if (this.alignment == NGUIText.Alignment.Automatic)
        {
            UIWidget.Pivot pivot = base.pivot;
            if (pivot == UIWidget.Pivot.Left || pivot == UIWidget.Pivot.TopLeft || pivot == UIWidget.Pivot.BottomLeft)
            {
                NGUIText.alignment = NGUIText.Alignment.Left;
            }
            else if (pivot == UIWidget.Pivot.Right || pivot == UIWidget.Pivot.TopRight || pivot == UIWidget.Pivot.BottomRight)
            {
                NGUIText.alignment = NGUIText.Alignment.Right;
            }
            else
            {
                NGUIText.alignment = NGUIText.Alignment.Center;
            }
        }
        else
        {
            NGUIText.alignment = this.alignment;
        }
        NGUIText.Update();
    }
Ejemplo n.º 17
0
	/// <summary>
	/// Special case version of Show() designed for menu bars. This not only ondoes
	/// HideMenuBar(), it also will, if necessary, build the entire menu hierarchy,
	/// though it will avoid doing so if it can. For non-menu bar menus this is
	/// a no-op. Normally you would not need to call this unless you have hidden
	/// the menu bar yourself, as it will be called at startup automatically.
	/// </summary>
	public void ShowMenuBar()
	{
		if (menuBar)
		{
			CtxHelper.SetActive(gameObject, true);

			// Avoid rebuilding the menu bar if it's already created.
			
			if (menuRoot != null)
			{
				if (panel == null)
					panel = NGUITools.FindInParents<UIPanel>(gameObject);
				
				if (panel != null)
					Refresh();
			}
			else
			{
				// Menu bars use their own positioning logic. It is assumed that the menu bar
				// will choose an edge of the screen based on the specified pivot. Horizontal
				// menu bars will prefer the top or bottom, while vertical menu bars will prefer
				// the left or right edge. It is also assumed that the menu bar is under a
				// UIAnchor that has an appropriate Side setting, which is why the menu bar
				// position is always 0,0,0.
				
				if (style == Style.Horizontal)
				{
					switch (pivot)
					{
					default:
					case UIWidget.Pivot.Top:
						pivot = UIWidget.Pivot.TopLeft;
						break;
					case UIWidget.Pivot.Bottom:
					case UIWidget.Pivot.BottomLeft:
					case UIWidget.Pivot.BottomRight:
						pivot = UIWidget.Pivot.BottomLeft;
						break;
					}
					
					Show(Vector3.zero);
				}
				else if (style == Style.Vertical)
				{
					switch (pivot)
					{
					default:
					case UIWidget.Pivot.Left:
					case UIWidget.Pivot.TopLeft:
					case UIWidget.Pivot.BottomLeft:
						pivot = UIWidget.Pivot.TopLeft;
						break;
					case UIWidget.Pivot.Right:
					case UIWidget.Pivot.TopRight:
					case UIWidget.Pivot.BottomRight:
						pivot = UIWidget.Pivot.TopRight;
						break;
					}
					
					Show(Vector3.zero);
				}
			}
		}
	}
Ejemplo n.º 18
0
    /// <summary>
    /// Determine what kind of pivot point is under the mouse and update the cursor accordingly.
    /// </summary>

    static public UIWidget.Pivot GetPivotUnderMouse(Vector3[] worldPos, Event e, bool[] resizable, bool movable, ref Action action)
    {
        // TimeToShake to figure out what kind of action is underneath the mouse
        UIWidget.Pivot pivotUnderMouse = UIWidget.Pivot.Center;

        if (action == Action.None)
        {
            int   index = 0;
            float dist  = GetScreenDistance(worldPos, e.mousePosition, out index);
            bool  alt   = (e.modifiers & EventModifiers.Alt) != 0;

            if (resizable[index] && dist < 10f)
            {
                pivotUnderMouse = pivotPoints[index];
                action          = Action.Scale;
            }
            else if (!alt && NGUIEditorTools.SceneViewDistanceToRectangle(worldPos, e.mousePosition) == 0f)
            {
                action = movable ? Action.Move : Action.Rotate;
            }
            else if (dist < 30f)
            {
                action = Action.Rotate;
            }
        }

        // Change the mouse cursor to a more appropriate one
#if !UNITY_3_5
        {
            Vector2[] screenPos = new Vector2[8];
            for (int i = 0; i < 8; ++i)
            {
                screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);
            }

            Bounds b = new Bounds(screenPos[0], Vector3.zero);
            for (int i = 1; i < 8; ++i)
            {
                b.Encapsulate(screenPos[i]);
            }

            Vector2 min = b.min;
            Vector2 max = b.max;

            min.x -= 30f;
            max.x += 30f;
            min.y -= 30f;
            max.y += 30f;

            Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);

            if (action == Action.Rotate)
            {
                SetCursorRect(rect, MouseCursor.RotateArrow);
            }
            else if (action == Action.Move)
            {
                SetCursorRect(rect, MouseCursor.MoveArrow);
            }
            else if (action == Action.Scale)
            {
                SetCursorRect(rect, MouseCursor.ScaleArrow);
            }
            else
            {
                SetCursorRect(rect, MouseCursor.Arrow);
            }
        }
#endif
        return(pivotUnderMouse);
    }
Ejemplo n.º 19
0
	/// <summary>
	/// Labels used for input shouldn't support color encoding.
	/// </summary>

	protected void Init ()
	{
		if (mDoInit)
		{
			mDoInit = false;
			if (label == null) label = GetComponentInChildren<UILabel>();

			if (label != null)
			{
				if (useLabelTextAtStart) mText = label.text;
				mDefaultText = label.text;
				mDefaultColor = label.color;
				label.supportEncoding = false;
				label.password = isPassword;
				label.maxLineCount = 1;
				mPivot = label.pivot;
				mPosition = label.cachedTransform.localPosition.x;
			}
			else enabled = false;
		}
	}
Ejemplo n.º 20
0
    private void SetMessage(string message)
    {
        //IL_0035: Unknown result type (might be due to invalid IL or missing references)
        //IL_003a: Unknown result type (might be due to invalid IL or missing references)
        //IL_0055: Unknown result type (might be due to invalid IL or missing references)
        //IL_005a: Unknown result type (might be due to invalid IL or missing references)
        //IL_0070: Unknown result type (might be due to invalid IL or missing references)
        //IL_0075: Unknown result type (might be due to invalid IL or missing references)
        //IL_0086: Unknown result type (might be due to invalid IL or missing references)
        //IL_008c: Unknown result type (might be due to invalid IL or missing references)
        //IL_00a7: Unknown result type (might be due to invalid IL or missing references)
        //IL_00ad: Unknown result type (might be due to invalid IL or missing references)
        //IL_010e: Unknown result type (might be due to invalid IL or missing references)
        //IL_0114: Unknown result type (might be due to invalid IL or missing references)
        //IL_0119: Unknown result type (might be due to invalid IL or missing references)
        //IL_011e: Unknown result type (might be due to invalid IL or missing references)
        //IL_012d: Unknown result type (might be due to invalid IL or missing references)
        //IL_0132: Unknown result type (might be due to invalid IL or missing references)
        //IL_0137: Unknown result type (might be due to invalid IL or missing references)
        //IL_0140: Unknown result type (might be due to invalid IL or missing references)
        //IL_0150: Unknown result type (might be due to invalid IL or missing references)
        //IL_0156: Unknown result type (might be due to invalid IL or missing references)
        //IL_0172: Unknown result type (might be due to invalid IL or missing references)
        //IL_0177: Unknown result type (might be due to invalid IL or missing references)
        //IL_0199: Unknown result type (might be due to invalid IL or missing references)
        //IL_019e: Unknown result type (might be due to invalid IL or missing references)
        //IL_01bf: 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_01df: 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_0200: Unknown result type (might be due to invalid IL or missing references)
        //IL_0214: Unknown result type (might be due to invalid IL or missing references)
        //IL_0241: Unknown result type (might be due to invalid IL or missing references)
        //IL_0252: Unknown result type (might be due to invalid IL or missing references)
        //IL_0257: Unknown result type (might be due to invalid IL or missing references)
        //IL_025c: Unknown result type (might be due to invalid IL or missing references)
        //IL_0290: Unknown result type (might be due to invalid IL or missing references)
        //IL_02a5: Unknown result type (might be due to invalid IL or missing references)
        //IL_02b9: Unknown result type (might be due to invalid IL or missing references)
        //IL_02e6: Unknown result type (might be due to invalid IL or missing references)
        //IL_02f7: Unknown result type (might be due to invalid IL or missing references)
        //IL_02fc: Unknown result type (might be due to invalid IL or missing references)
        //IL_0301: Unknown result type (might be due to invalid IL or missing references)
        //IL_033b: Unknown result type (might be due to invalid IL or missing references)
        m_LabelMessage.text  = message;
        m_LabelMessage.pivot = (isMyMessage ? UIWidget.Pivot.TopRight : UIWidget.Pivot.TopLeft);
        if (isMyMessage)
        {
            Vector3 mESSAGE_LABEL_POSITION_SELF = MESSAGE_LABEL_POSITION_SELF;
            float   x           = mESSAGE_LABEL_POSITION_SELF.x;
            float   num         = (float)m_LabelMessage.width;
            Vector2 printedSize = m_LabelMessage.printedSize;
            mESSAGE_LABEL_POSITION_SELF.x = x + (num - printedSize.x);
            m_LabelMessage.get_transform().set_localPosition(mESSAGE_LABEL_POSITION_SELF);
        }
        else
        {
            m_LabelMessage.get_transform().set_localPosition(MESSAGE_LABEL_POSITION_OTHER);
        }
        if (isNotifi)
        {
            m_LabelMessage.get_transform().set_localPosition(MESSAGE_LABEL_POSITION_NOTIFI);
        }
        GameObject val = (!isMyMessage) ? m_PivotMessaageLeft : m_PivotMessageRight;

        UIWidget.Pivot pivot      = isMyMessage ? UIWidget.Pivot.TopRight : UIWidget.Pivot.TopLeft;
        string         spriteName = (!isMyMessage) ? "ChatHukidashiBlue" : "ChatHukidashiMine";

        if (isNotifi)
        {
            Transform transform      = val.get_transform();
            Vector3   localPosition  = val.get_transform().get_localPosition();
            float     x2             = localPosition.x;
            Vector3   localPosition2 = val.get_transform().get_localPosition();
            transform.set_localPosition(new Vector3(x2, 0f, localPosition2.z));
        }
        m_SpriteBase.get_transform().set_parent(val.get_transform());
        m_SpriteBase.pivot = pivot;
        m_SpriteBase.get_transform().set_localPosition(Vector3.get_zero());
        m_SpriteBase.spriteName = spriteName;
        UISprite spriteBase   = m_SpriteBase;
        Vector2  printedSize2 = m_LabelMessage.printedSize;

        spriteBase.width = (int)(printedSize2.x + 50f);
        UISprite spriteBase2  = m_SpriteBase;
        Vector2  printedSize3 = m_LabelMessage.printedSize;

        spriteBase2.height = (int)(printedSize3.y + 25f);
        m_PinButton.get_transform().SetParent(val.get_transform());
        if (isMyMessage)
        {
            m_PinButton.get_transform().set_localPosition(new Vector3(-55f, 0f, 0f));
            m_BoxCollider.set_size(new Vector3((float)m_SpriteBase.width, (float)m_SpriteBase.height, 1f));
            BoxCollider boxCollider    = m_BoxCollider;
            Vector3     localPosition3 = val.get_transform().get_localPosition();
            boxCollider.set_center(new Vector3(localPosition3.x - (float)m_SpriteBase.width / 2f, (0f - (float)m_SpriteBase.height) / 2f, 0f));
        }
        else
        {
            m_PinButton.get_transform().set_localPosition(new Vector3(55f, 0f, 0f));
            m_BoxCollider.set_size(new Vector3((float)m_SpriteBase.width, (float)m_SpriteBase.height, 1f));
            BoxCollider boxCollider2   = m_BoxCollider;
            Vector3     localPosition4 = val.get_transform().get_localPosition();
            boxCollider2.set_center(new Vector3(localPosition4.x + (float)m_SpriteBase.width / 2f, (0f - (float)m_SpriteBase.height) / 2f - 16f, 0f));
        }
    }
Ejemplo n.º 21
0
 static bool IsBottom(UIWidget.Pivot pivot)
 {
     return(pivot == UIWidget.Pivot.Bottom ||
            pivot == UIWidget.Pivot.BottomLeft ||
            pivot == UIWidget.Pivot.BottomRight);
 }
Ejemplo n.º 22
0
    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(130f);

        GUILayout.Space(3f);
        serializedObject.Update();

        SerializedProperty sppv = serializedObject.FindProperty("contentPivot");

        UIWidget.Pivot before = (UIWidget.Pivot)sppv.intValue;

        NGUIEditorTools.DrawProperty("Content Origin", sppv, false);

        SerializedProperty movement        = NGUIEditorTools.DrawProperty("Movement", serializedObject, "movement");
        SerializedProperty customMovementX = null;
        SerializedProperty customMovementY = null;

        if (((UIScrollView.Movement)movement.intValue) == UIScrollView.Movement.Custom)
        {
            NGUIEditorTools.SetLabelWidth(20f);

            GUILayout.BeginHorizontal();
            GUILayout.Space(114f);
            customMovementX = NGUIEditorTools.DrawProperty("X", serializedObject, "customMovement.x", GUILayout.MinWidth(20f));
            customMovementY = NGUIEditorTools.DrawProperty("Y", serializedObject, "customMovement.y", GUILayout.MinWidth(20f));
            GUILayout.EndHorizontal();
        }

        NGUIEditorTools.SetLabelWidth(130f);

        NGUIEditorTools.DrawProperty("Drag Effect", serializedObject, "dragEffect");
        NGUIEditorTools.DrawProperty("Scroll Wheel Factor", serializedObject, "scrollWheelFactor");
        NGUIEditorTools.DrawProperty("Momentum Amount", serializedObject, "momentumAmount");

        SerializedProperty restrict = NGUIEditorTools.DrawProperty("Restrict Within Panel", serializedObject, "restrictWithinPanel");

        if (restrict.boolValue == true)
        {
            if (CanMoveHorizontally((UIScrollView.Movement)movement.intValue, customMovementX != null ? customMovementX.floatValue : 0f))
            {
                NGUIEditorTools.DrawProperty("Constrain To Left", serializedObject, "constrainToLeft");
            }
            if (CanMoveVertically((UIScrollView.Movement)movement.intValue, customMovementY != null ? customMovementY.floatValue : 0f))
            {
                NGUIEditorTools.DrawProperty("Constrain To Top", serializedObject, "constrainToTop");
            }
        }
        NGUIEditorTools.DrawProperty("Cancel Drag If Fits", serializedObject, "disableDragIfFits");
        NGUIEditorTools.DrawProperty("Smooth Drag Start", serializedObject, "smoothDragStart");
        NGUIEditorTools.DrawProperty("IOS Drag Emulation", serializedObject, "iOSDragEmulation");

        NGUIEditorTools.SetLabelWidth(100f);

        if (NGUIEditorTools.DrawHeader("Scroll Bars"))
        {
            NGUIEditorTools.BeginContents();
            NGUIEditorTools.DrawProperty("Horizontal", serializedObject, "horizontalScrollBar");
            NGUIEditorTools.DrawProperty("Vertical", serializedObject, "verticalScrollBar");
            NGUIEditorTools.DrawProperty("Show Condition", serializedObject, "showScrollBars");
            NGUIEditorTools.EndContents();
        }
        serializedObject.ApplyModifiedProperties();

        if (before != (UIWidget.Pivot)sppv.intValue)
        {
            (target as UIScrollView).ResetPosition();
        }
    }
Ejemplo n.º 23
0
	/// <summary>
	/// Labels used for input shouldn't support rich text.
	/// </summary>

	protected void Init ()
	{
		if (mDoInit && label != null)
		{
			mDoInit = false;
			mDefaultText = label.text;
			mDefaultColor = label.color;
			label.supportEncoding = false;

			if (label.alignment == NGUIText.Alignment.Justified)
			{
				label.alignment = NGUIText.Alignment.Left;
				Debug.LogWarning("Input fields using labels with justified alignment are not supported at this time", this);
			}

			mPivot = label.pivot;
			mPosition = label.cachedTransform.localPosition.x;
			UpdateLabel();
		}
	}
Ejemplo n.º 24
0
    void Update()
    {
        alphaMod = Mathf.MoveTowards(alphaMod, (isEnabled && !aimingAt) ? 1f : 0f, Time.unscaledDeltaTime * 5f);
        foreach (UIWidget widget in widgets)
        {
            widget.alpha = widget.defaultAlpha * alphaMod * osMod;
        }

        if (target != null)
        {
            BaseStats bs = target.GetComponent <BaseStats>();
            targetDead = (bs != null && bs.curHealth <= 0);
        }

        if (target == null || targetDead)
        {
            isEnabled = false;
        }

        if (!isEnabled && alphaMod <= 0f)
        {
            return;
        }

        curWidth = normalWidth;
        if (DarkRef.isModernWidescreen)
        {
            curWidth = modernWideWidth;
        }
        else if (DarkRef.isOldWidescreen)
        {
            curWidth = oldWideWidth;
        }

        curScale = (scalingEnabled) ? DarkRef.ScaleWithDistance(distance, nearDistance, farDistance, nearScale, farScale) : 1f;

        if (mainCamera == null)
        {
            return;
        }

        if (target != null)
        {
            m_LastPos = target.position;
            pos       = GetBasicViewportPosition(target.position);
        }
        else
        {
            pos = GetBasicViewportPosition(m_LastPos);
        }

        Vector3 currentTarget = (target == null) ? m_LastPos : target.position;

        if (pos.z < 0f)
        {
            pos = GetAdvancedViewportPosition(currentTarget, 1.0f, pos);
        }
        else if (pos.x < 0f)
        {
            if (pos.x <= -1.0f)
            {
                pos = GetAdvancedViewportPosition(currentTarget, 1.0f, pos);
            }
            else
            {
                pos = GetAdvancedViewportPosition(currentTarget, 1.0f - (1.0f - Mathf.Abs(pos.x)), pos);
            }
        }
        else if (pos.x > 1.0f)
        {
            if (pos.x >= 2.0f)
            {
                pos = GetAdvancedViewportPosition(currentTarget, 1.0f, pos);
            }
            else
            {
                pos = GetAdvancedViewportPosition(currentTarget, 1.0f - (1.0f - (pos.x - 1.0f)), pos);
            }
        }
        else if (pos.y < 0f)
        {
            if (pos.y <= -1.0f)
            {
                pos = GetAdvancedViewportPosition(currentTarget, 1.0f, pos);
            }
            else
            {
                pos = GetAdvancedViewportPosition(currentTarget, 1.0f - (1.0f - Mathf.Abs(pos.x)), pos);
            }
        }
        else if (pos.y > 2.0f)
        {
            if (pos.y >= 2.0f)
            {
                pos = GetAdvancedViewportPosition(currentTarget, 1.0f, pos);
            }
            else
            {
                pos = GetAdvancedViewportPosition(currentTarget, 1.0f - (1.0f - (pos.y - 1.0f)), pos);
            }
        }

        int markerX = Mathf.RoundToInt(-curWidth + (pos.x * curWidth * 2f));
        int markerY = Mathf.RoundToInt(-normalHeight + (pos.y * normalHeight * 2f));

        rotation = 0f;
        if (pos.x > 0f && pos.x < 1f && pos.y > 0f && pos.y < 1f)
        {
            markerPos  = new Vector2(markerX, markerY);
            curOffset  = Vector2.zero;
            curTexture = GUITextures[0];
        }
        else if (pos.x <= 0f)
        {
            if (pos.y <= 0f)
            {
                markerPos  = new Vector2(-curWidth, -normalHeight);
                curOffset  = new Vector2(edgeOffset.x, edgeOffset.y);
                curTexture = GUITextures[3];
                rotation   = 135f;
            }
            else if (pos.y >= 1f)
            {
                markerPos  = new Vector2(-curWidth, normalHeight);
                curOffset  = new Vector2(edgeOffset.x, -edgeOffset.y);
                curTexture = GUITextures[3];
                rotation   = 45f;
            }
            else
            {
                markerPos  = new Vector2(-curWidth, Mathf.Clamp(markerY, -normalHeight, normalHeight));
                curOffset  = new Vector2(edgeOffset.x, 0f);
                curTexture = GUITextures[1];
            }
        }
        else if (pos.x >= 1f)
        {
            if (pos.y <= 0f)
            {
                markerPos  = new Vector2(curWidth, -normalHeight);
                curOffset  = new Vector2(-edgeOffset.x, edgeOffset.y);
                curTexture = GUITextures[3];
                rotation   = -135f;
            }
            else if (pos.y >= 1f)
            {
                markerPos  = new Vector2(curWidth, normalHeight);
                curOffset  = new Vector2(-edgeOffset.x, -edgeOffset.y);
                curTexture = GUITextures[3];
                rotation   = -45f;
            }
            else
            {
                markerPos  = new Vector2(curWidth, Mathf.Clamp(markerY, -normalHeight, normalHeight));
                curOffset  = new Vector2(-edgeOffset.x, 0f);
                curTexture = GUITextures[2];
            }
        }
        else if (pos.y <= 0f)
        {
            markerPos  = new Vector2(markerX, -normalHeight);
            curOffset  = new Vector2(0f, edgeOffset.y);
            curTexture = GUITextures[4];
        }
        else if (pos.y >= 1f)
        {
            markerPos  = new Vector2(markerX, normalHeight);
            curOffset  = new Vector2(0f, -edgeOffset.y);
            curTexture = GUITextures[3];
        }

        osMod = (pos.x <= 0f || pos.x >= 1f || pos.y <= 0f || pos.y >= 1f) ? 0.35f : 1f;

        if (markerTexture.mainTexture != curTexture)
        {
            markerTexture.mainTexture = curTexture;
        }

        if (pos.x <= textBorder.x)
        {
            pivotPoint = UIWidget.Pivot.Left;
            xText      = -12f;
        }
        else if (pos.x >= textBorder.y)
        {
            pivotPoint = UIWidget.Pivot.Right;
            xText      = 12f;
        }
        else
        {
            pivotPoint = UIWidget.Pivot.Center;
            xText      = 0f;
        }

        if (distanceLabel.pivot != pivotPoint)
        {
            distanceLabel.pivot    = pivotPoint;
            descriptionLabel.pivot = pivotPoint;
        }

        if (pos.y <= textBorder.z)
        {
            yText  = 32f;
            yText2 = 20f;
        }
        else
        {
            yText  = -20f;
            yText2 = -33f;
        }

        offsetReal = Vector2.Lerp(offsetReal, curOffset, Time.unscaledDeltaTime * 5f);

        distanceLabel.cachedTrans.localPosition    = Vector3.Lerp(distanceLabel.cachedTrans.localPosition, new Vector3(xText, yText, 0f), Time.unscaledDeltaTime * 10f);
        descriptionLabel.cachedTrans.localPosition = Vector3.Lerp(descriptionLabel.cachedTrans.localPosition, new Vector3(xText, yText2, 0f), Time.unscaledDeltaTime * 10f);

        tr.localPosition = markerPos + offsetReal;

        markerTexture.cachedTrans.localRotation = Quaternion.Slerp(markerTexture.cachedTrans.localRotation, Quaternion.Euler(0f, 0f, rotation), Time.unscaledDeltaTime * 8f);
        aimingAt = (ac != null && ac.isAiming && Mathf.Abs(pos.x - 0.5f) < 0.2f && Mathf.Abs(pos.y - 0.5f) < 0.2f);
    }
Ejemplo n.º 25
0
        public void CheckOutOfBounds(Vector3 size, UIWidget.Pivot pivot)
        {
            if (null == panel)
            {
                return;
            }
            float   boundsMin = 0, boundsMax = 0;
            float   space      = GetMinMaxOffset(size, pivot, ref boundsMin, ref boundsMax);
            Vector3 oriPos     = mTrans.localPosition;
            Vector2 clipOffset = panel.clipOffset;

            switch (movement)
            {
            case Movement.Horizontal:
            {
                float offPos = oriPos.x + clipOffset.x;
                if (space < 0)
                {
                    clipOffset.x = boundsMax;
                }
                else
                {
                    if (clipOffset.x < boundsMin)
                    {
                        clipOffset.x = boundsMin;
                    }
                    else if (clipOffset.x > boundsMax)
                    {
                        clipOffset.x = boundsMax;
                    }
                }
                oriPos.x             = offPos + -clipOffset.x;
                mTrans.localPosition = oriPos;
                panel.clipOffset     = clipOffset;
            }
            break;

            case Movement.Vertical:
            {
                float offPos = oriPos.y + clipOffset.y;
                if (space < 0)
                {
                    clipOffset.y = boundsMin;
                }
                else
                {
                    if (clipOffset.y < boundsMin)
                    {
                        clipOffset.y = boundsMin;
                    }
                    else if (clipOffset.y > boundsMax)
                    {
                        clipOffset.y = boundsMax;
                    }
                }
                oriPos.y             = offPos + -clipOffset.y;
                mTrans.localPosition = oriPos;
                panel.clipOffset     = clipOffset;
            }
            break;
            }
        }
    /// <summary>
    /// All widgets have depth, color and make pixel-perfect options
    /// </summary>

    protected void DrawCommonProperties()
    {
        PrefabType type = PrefabUtility.GetPrefabType(mWidget.gameObject);

        if (NGUIEditorTools.DrawHeader("Widget"))
        {
            NGUIEditorTools.BeginContents();

            // Color tint
            GUILayout.BeginHorizontal();
            Color color = EditorGUILayout.ColorField("Color Tint", mWidget.color);
            if (GUILayout.Button("Copy", GUILayout.Width(50f)))
            {
                NGUISettings.color = color;
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            NGUISettings.color = EditorGUILayout.ColorField("Clipboard", NGUISettings.color);
            if (GUILayout.Button("Paste", GUILayout.Width(50f)))
            {
                color = NGUISettings.color;
            }
            GUILayout.EndHorizontal();

            if (mWidget.color != color)
            {
                NGUIEditorTools.RegisterUndo("Color Change", mWidget);
                mWidget.color = color;
            }

            GUILayout.Space(6f);

#if UNITY_3_5
            // Pivot point -- old school drop-down style
            UIWidget.Pivot pivot = (UIWidget.Pivot)EditorGUILayout.EnumPopup("Pivot", mWidget.pivot);

            if (mWidget.pivot != pivot)
            {
                NGUIEditorTools.RegisterUndo("Pivot Change", mWidget);
                mWidget.pivot = pivot;
            }
#else
            // Pivot point -- the new, more visual style
            GUILayout.BeginHorizontal();
            GUILayout.Label("Pivot", GUILayout.Width(76f));
            Toggle("\u25C4", "ButtonLeft", UIWidget.Pivot.Left, true);
            Toggle("\u25AC", "ButtonMid", UIWidget.Pivot.Center, true);
            Toggle("\u25BA", "ButtonRight", UIWidget.Pivot.Right, true);
            Toggle("\u25B2", "ButtonLeft", UIWidget.Pivot.Top, false);
            Toggle("\u258C", "ButtonMid", UIWidget.Pivot.Center, false);
            Toggle("\u25BC", "ButtonRight", UIWidget.Pivot.Bottom, false);
            GUILayout.EndHorizontal();
#endif
            // Depth navigation
            if (type != PrefabType.Prefab)
            {
                GUILayout.Space(2f);
                GUILayout.BeginHorizontal();
                {
                    EditorGUILayout.PrefixLabel("Depth");

                    int depth = mWidget.depth;
                    if (GUILayout.Button("Back", GUILayout.Width(60f)))
                    {
                        --depth;
                    }
                    depth = EditorGUILayout.IntField(depth, GUILayout.MinWidth(20f));
                    if (GUILayout.Button("Forward", GUILayout.Width(68f)))
                    {
                        ++depth;
                    }

                    if (mWidget.depth != depth)
                    {
                        NGUIEditorTools.RegisterUndo("Depth Change", mWidget);
                        mWidget.depth = depth;
                    }
                }
                GUILayout.EndHorizontal();

                int matchingDepths = 0;

                for (int i = 0; i < UIWidget.list.size; ++i)
                {
                    UIWidget w = UIWidget.list[i];
                    if (w != null && w.panel != null && mWidget.panel != null &&
                        w.panel.depth == mWidget.panel.depth && w.depth == mWidget.depth)
                    {
                        ++matchingDepths;
                    }
                }

                if (matchingDepths > 1)
                {
                    EditorGUILayout.HelpBox(matchingDepths + " widgets are sharing the depth value of " + mWidget.depth, MessageType.Info);
                }
            }

            GUI.changed = false;
            GUILayout.BeginHorizontal();
            int width = EditorGUILayout.IntField("Dimensions", mWidget.width, GUILayout.Width(128f));
            NGUIEditorTools.SetLabelWidth(12f);
            int height = EditorGUILayout.IntField("x", mWidget.height, GUILayout.MinWidth(30f));
            NGUIEditorTools.SetLabelWidth(80f);

            if (GUI.changed)
            {
                NGUIEditorTools.RegisterUndo("Widget Change", mWidget);
                mWidget.width  = width;
                mWidget.height = height;
            }

            if (type != PrefabType.Prefab)
            {
                if (GUILayout.Button("Correct", GUILayout.Width(68f)))
                {
                    NGUIEditorTools.RegisterUndo("Widget Change", mWidget);
                    NGUIEditorTools.RegisterUndo("Make Pixel-Perfect", mWidget.transform);
                    mWidget.MakePixelPerfect();
                }
            }
            else
            {
                GUILayout.Space(70f);
            }
            GUILayout.EndHorizontal();
            NGUIEditorTools.EndContents();
        }
    }
Ejemplo n.º 27
0
    protected void SlicedFill(BetterList <Vector3> verts, BetterList <Vector2> uvs, BetterList <Color32> cols)
    {
        if (this.mOuterUV == this.mInnerUV)
        {
            this.SimpleFill(verts, uvs, cols);
        }
        else
        {
            Vector2[] vectorArray  = new Vector2[4];
            Vector2[] vectorArray2 = new Vector2[4];
            Texture   mainTexture  = this.mainTexture;
            vectorArray[0] = Vector2.zero;
            vectorArray[1] = Vector2.zero;
            vectorArray[2] = new Vector2(1f, -1f);
            vectorArray[3] = new Vector2(1f, -1f);
            if (mainTexture == null)
            {
                for (int j = 0; j < 4; j++)
                {
                    vectorArray2[j] = Vector2.zero;
                }
            }
            else
            {
                float   pixelSize  = this.atlas.pixelSize;
                float   num2       = (this.mInnerUV.xMin - this.mOuterUV.xMin) * pixelSize;
                float   num3       = (this.mOuterUV.xMax - this.mInnerUV.xMax) * pixelSize;
                float   num4       = (this.mInnerUV.yMax - this.mOuterUV.yMax) * pixelSize;
                float   num5       = (this.mOuterUV.yMin - this.mInnerUV.yMin) * pixelSize;
                Vector3 localScale = base.cachedTransform.localScale;
                localScale.x = Mathf.Max(0f, localScale.x);
                localScale.y = Mathf.Max(0f, localScale.y);
                Vector2        vector2 = new Vector2(localScale.x / ((float)mainTexture.width), localScale.y / ((float)mainTexture.height));
                Vector2        vector3 = new Vector2(num2 / vector2.x, num4 / vector2.y);
                Vector2        vector4 = new Vector2(num3 / vector2.x, num5 / vector2.y);
                UIWidget.Pivot pivot   = base.pivot;
                switch (pivot)
                {
                case UIWidget.Pivot.Right:
                case UIWidget.Pivot.TopRight:
                case UIWidget.Pivot.BottomRight:
                    vectorArray[0].x = Mathf.Min((float)0f, (float)(1f - (vector4.x + vector3.x)));
                    vectorArray[1].x = vectorArray[0].x + vector3.x;
                    vectorArray[2].x = vectorArray[0].x + Mathf.Max(vector3.x, 1f - vector4.x);
                    vectorArray[3].x = vectorArray[0].x + Mathf.Max((float)(vector3.x + vector4.x), (float)1f);
                    break;

                default:
                    vectorArray[1].x = vector3.x;
                    vectorArray[2].x = Mathf.Max(vector3.x, 1f - vector4.x);
                    vectorArray[3].x = Mathf.Max((float)(vector3.x + vector4.x), (float)1f);
                    break;
                }
                switch (pivot)
                {
                case UIWidget.Pivot.Bottom:
                case UIWidget.Pivot.BottomLeft:
                case UIWidget.Pivot.BottomRight:
                    vectorArray[0].y = Mathf.Max((float)0f, (float)(-1f - (vector4.y + vector3.y)));
                    vectorArray[1].y = vectorArray[0].y + vector3.y;
                    vectorArray[2].y = vectorArray[0].y + Mathf.Min(vector3.y, -1f - vector4.y);
                    vectorArray[3].y = vectorArray[0].y + Mathf.Min((float)(vector3.y + vector4.y), (float)-1f);
                    break;

                default:
                    vectorArray[1].y = vector3.y;
                    vectorArray[2].y = Mathf.Min(vector3.y, -1f - vector4.y);
                    vectorArray[3].y = Mathf.Min((float)(vector3.y + vector4.y), (float)-1f);
                    break;
                }
                vectorArray2[0] = new Vector2(this.mOuterUV.xMin, this.mOuterUV.yMax);
                vectorArray2[1] = new Vector2(this.mInnerUV.xMin, this.mInnerUV.yMax);
                vectorArray2[2] = new Vector2(this.mInnerUV.xMax, this.mInnerUV.yMin);
                vectorArray2[3] = new Vector2(this.mOuterUV.xMax, this.mOuterUV.yMin);
            }
            Color c = base.color;
            c.a *= base.mPanel.alpha;
            Color32 item = !this.atlas.premultipliedAlpha ? c : NGUITools.ApplyPMA(c);
            for (int i = 0; i < 3; i++)
            {
                int index = i + 1;
                for (int k = 0; k < 3; k++)
                {
                    if ((this.mFillCenter || (i != 1)) || (k != 1))
                    {
                        int num10 = k + 1;
                        verts.Add(new Vector3(vectorArray[index].x, vectorArray[k].y, 0f));
                        verts.Add(new Vector3(vectorArray[index].x, vectorArray[num10].y, 0f));
                        verts.Add(new Vector3(vectorArray[i].x, vectorArray[num10].y, 0f));
                        verts.Add(new Vector3(vectorArray[i].x, vectorArray[k].y, 0f));
                        uvs.Add(new Vector2(vectorArray2[index].x, vectorArray2[k].y));
                        uvs.Add(new Vector2(vectorArray2[index].x, vectorArray2[num10].y));
                        uvs.Add(new Vector2(vectorArray2[i].x, vectorArray2[num10].y));
                        uvs.Add(new Vector2(vectorArray2[i].x, vectorArray2[k].y));
                        cols.Add(item);
                        cols.Add(item);
                        cols.Add(item);
                        cols.Add(item);
                    }
                }
            }
        }
    }
    /// <summary>
    /// All widgets have depth, color and make pixel-perfect options
    /// </summary>
    protected void DrawCommonProperties()
    {
#if UNITY_3_4
        PrefabType type = EditorUtility.GetPrefabType(mWidget.gameObject);
#else
        PrefabType type = PrefabUtility.GetPrefabType(mWidget.gameObject);
#endif

        NGUIEditorTools.DrawSeparator();

        // Depth navigation
        if (type != PrefabType.Prefab)
        {
            GUILayout.BeginHorizontal();
            {
                EditorGUILayout.PrefixLabel("Depth");

                int depth = mWidget.depth;
                if (GUILayout.Button("Back"))
                {
                    --depth;
                }
                depth = EditorGUILayout.IntField(depth, GUILayout.Width(40f));
                if (GUILayout.Button("Forward"))
                {
                    ++depth;
                }

                if (mWidget.depth != depth)
                {
                    NGUIEditorTools.RegisterUndo("Depth Change", mWidget);
                    mWidget.depth = depth;
                }
            }
            GUILayout.EndHorizontal();
        }

        Color color = EditorGUILayout.ColorField("Color Tint", mWidget.color);

        if (mWidget.color != color)
        {
            NGUIEditorTools.RegisterUndo("Color Change", mWidget);
            mWidget.color = color;
        }

        // Depth navigation
        if (type != PrefabType.Prefab)
        {
            GUILayout.BeginHorizontal();
            {
                EditorGUILayout.PrefixLabel("Correction");

                if (GUILayout.Button("Make Pixel-Perfect"))
                {
                    NGUIEditorTools.RegisterUndo("Make Pixel-Perfect", mWidget.transform);
                    mWidget.MakePixelPerfect();
                }
            }
            GUILayout.EndHorizontal();
        }

        UIWidget.Pivot pivot = (UIWidget.Pivot)EditorGUILayout.EnumPopup("Pivot", mWidget.pivot);

        if (mWidget.pivot != pivot)
        {
            NGUIEditorTools.RegisterUndo("Pivot Change", mWidget);
            mWidget.pivot = pivot;
        }

        if (mAllowPreview && mWidget.mainTexture != null)
        {
            GUILayout.BeginHorizontal();
            {
                UISettings.texturePreview = EditorGUILayout.Toggle("Preview", UISettings.texturePreview, GUILayout.Width(100f));

                /*if (UISettings.texturePreview)
                 *              {
                 *                      if (mUseShader != EditorGUILayout.Toggle("Use Shader", mUseShader))
                 *                      {
                 *                              mUseShader = !mUseShader;
                 *
                 *                              if (mUseShader)
                 *                              {
                 *                                      // TODO: Remove this when Unity fixes the bug with DrawPreviewTexture not being affected by BeginGroup
                 *                                      Debug.LogWarning("There is a bug in Unity that prevents the texture from getting clipped properly.\n" +
                 *                                              "Until it's fixed by Unity, your texture may spill onto the rest of the Unity's GUI while using this mode.");
                 *                              }
                 *                      }
                 *              }*/
            }
            GUILayout.EndHorizontal();

            // Draw the texture last
            if (UISettings.texturePreview)
            {
                OnDrawTexture();
            }
        }
    }
	/// <summary>
	/// Draw the on-screen selection, knobs, and handle all interaction logic.
	/// </summary>

	public void OnSceneGUI ()
	{
		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);
		bool canResize = mWidget.canResize;
		UIWidget.Pivot pivotUnderMouse = GetPivotUnderMouse(handles, e, canResize, ref actionUnderMouse);

		Handles.color = handlesColor;
		Handles.DrawLine(handles[0], handles[1]);
		Handles.DrawLine(handles[1], handles[2]);
		Handles.DrawLine(handles[2], handles[3]);
		Handles.DrawLine(handles[0], handles[3]);
		
		switch (type)
		{
			case EventType.Repaint:
			{
				Vector3 bottomLeft = HandleUtility.WorldToGUIPoint(handles[0]);
				Vector3 topRight = HandleUtility.WorldToGUIPoint(handles[2]);
				Vector3 diff = topRight - bottomLeft;
				float mag = diff.magnitude;

				if (mag > 140f)
				{
					Handles.BeginGUI();
					{
						for (int i = 0; i < 8; ++i)
						{
							DrawKnob(handles[i], mWidget.pivot == pivotPoints[i], canResize, id);
						}
					}
					Handles.EndGUI();
				}
				else if (mag > 40f)
				{
					Handles.BeginGUI();
					{
						for (int i = 0; i < 4; ++i)
						{
							DrawKnob(handles[i], mWidget.pivot == pivotPoints[i], canResize, id);
						}
					}
					Handles.EndGUI();
				}
			}
			break;

			case EventType.MouseDown:
			{
				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))
				{
					mStartPos = t.position;
					mStartRot = t.localRotation.eulerAngles;
					mStartDir = mStartDrag - t.position;
					mStartWidth = mWidget.width;
					mStartHeight = mWidget.height;
					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);
										mStartPos = t.position;
										NGUIEditorTools.RegisterUndo("Move widget", t);
									}
									else if (mActionUnderMouse == Action.Rotate)
									{
										mStartRot = t.localRotation.eulerAngles;
										mStartDir = mStartDrag - t.position;
										NGUIEditorTools.RegisterUndo("Rotate widget", t);
									}
									else if (mActionUnderMouse == Action.Scale)
									{
										mStartPos = t.localPosition;
										mStartWidth = mWidget.width;
										mStartHeight = mWidget.height;
										mDragPivot = pivotUnderMouse;
										NGUIEditorTools.RegisterUndo("Scale widget", t);
										NGUIEditorTools.RegisterUndo("Scale widget", mWidget);
									}
									mAction = actionUnderMouse;
								}
							}

							if (mAction != Action.None)
							{
								if (mAction == Action.Move)
								{
									t.position = mStartPos + (pos - mStartDrag);
									t.localPosition = NGUISnap.Snap(t.localPosition, mWidget.localCorners,
										e.modifiers != EventModifiers.Control);
								}
								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)
								{
									// 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
									AdjustWidget(mWidget, mStartPos, mStartWidth, mStartHeight, delta, mDragPivot);
								}
							}
						}
					}
				}
			}
			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 == 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)
				{
					BetterList<UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
					if (widgets.size > 0) Selection.activeGameObject = widgets[0].gameObject;
				}
				mAllowSelection = true;
			}
			break;

			case EventType.KeyDown:
			{
				if (e.keyCode == KeyCode.UpArrow)
				{
					Vector3 pos = t.localPosition;
					pos.y += 1f;
					t.localPosition = pos;
					e.Use();
				}
				else if (e.keyCode == KeyCode.DownArrow)
				{
					Vector3 pos = t.localPosition;
					pos.y -= 1f;
					t.localPosition = pos;
					e.Use();
				}
				else if (e.keyCode == KeyCode.LeftArrow)
				{
					Vector3 pos = t.localPosition;
					pos.x -= 1f;
					t.localPosition = pos;
					e.Use();
				}
				else if (e.keyCode == KeyCode.RightArrow)
				{
					Vector3 pos = t.localPosition;
					pos.x += 1f;
					t.localPosition = pos;
					e.Use();
				}
				else if (e.keyCode == KeyCode.Escape)
				{
					if (GUIUtility.hotControl == id)
					{
						if (mAction != Action.None)
						{
							if (mAction == Action.Move)
							{
								t.position = mStartPos;
							}
							else if (mAction == Action.Rotate)
							{
								t.localRotation = Quaternion.Euler(mStartRot);
							}
							else if (mAction == Action.Scale)
							{
								t.position = mStartPos;
								mWidget.width = mStartWidth;
								mWidget.height = mStartHeight;
							}
						}

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

						mActionUnderMouse = Action.None;
						mAction = Action.None;
						e.Use();
					}
					else Selection.activeGameObject = null;
				}
			}
			break;
		}
	}
Ejemplo n.º 30
0
    static void Load()
    {
        int l = LayerMask.NameToLayer("UI");
        if (l == -1) l = LayerMask.NameToLayer("GUI");
        if (l == -1) l = 31;

        mLoaded			= true;
        mPartial		= EditorPrefs.GetString("NGUI Partial");
        mFontName		= EditorPrefs.GetString("NGUI Font Name");
        mAtlasName		= EditorPrefs.GetString("NGUI Atlas Name");
        mFontData		= GetObject("NGUI Font Asset") as TextAsset;
        mFontTexture	= GetObject("NGUI Font Texture") as Texture2D;
        mFont			= GetObject("NGUI Font") as UIFont;
        mAtlas			= GetObject("NGUI Atlas") as UIAtlas;
        mAtlasPadding	= EditorPrefs.GetInt("NGUI Atlas Padding", 1);
        mAtlasTrimming	= EditorPrefs.GetBool("NGUI Atlas Trimming", true);
        mUnityPacking	= EditorPrefs.GetBool("NGUI Unity Packing", true);
        mForceSquare	= EditorPrefs.GetBool("NGUI Force Square Atlas", true);
        mPivot			= (UIWidget.Pivot)EditorPrefs.GetInt("NGUI Pivot", (int)mPivot);
        mLayer			= EditorPrefs.GetInt("NGUI Layer", l);
        mDynFont		= GetObject("NGUI DynFont") as Font;
        mDynFontSize	= EditorPrefs.GetInt("NGUI DynFontSize", 16);
        mDynFontStyle	= (FontStyle)EditorPrefs.GetInt("NGUI DynFontStyle", (int)FontStyle.Normal);

        LoadColor();
    }
Ejemplo n.º 31
0
    /// <summary>
    /// Handles & interaction.
    /// </summary>

    public void OnSceneGUI()
    {
        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)
            {
                BetterList <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.size > 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;
        }
    }
Ejemplo n.º 32
0
    /// <summary>
    /// All widgets have depth, color and make pixel-perfect options
    /// </summary>

    protected void DrawCommonProperties()
    {
        PrefabType type = PrefabUtility.GetPrefabType(mWidget.gameObject);

        NGUIEditorTools.DrawSeparator();

#if UNITY_3_5
        // Pivot point -- old school drop-down style
        UIWidget.Pivot pivot = (UIWidget.Pivot)EditorGUILayout.EnumPopup("Pivot", mWidget.pivot);

        if (mWidget.pivot != pivot)
        {
            NGUIEditorTools.RegisterUndo("Pivot Change", mWidget);
            mWidget.pivot = pivot;
        }
#else
        // Pivot point -- the new, more visual style
        GUILayout.BeginHorizontal();
        GUILayout.Label("Pivot", GUILayout.Width(76f));
        Toggle("◄", "ButtonLeft", UIWidget.Pivot.Left, true);
        Toggle("▬", "ButtonMid", UIWidget.Pivot.Center, true);
        Toggle("►", "ButtonRight", UIWidget.Pivot.Right, true);
        Toggle("▲", "ButtonLeft", UIWidget.Pivot.Top, false);
        Toggle("▌", "ButtonMid", UIWidget.Pivot.Center, false);
        Toggle("▼", "ButtonRight", UIWidget.Pivot.Bottom, false);
        GUILayout.EndHorizontal();
#endif

        // Depth navigation
        if (type != PrefabType.Prefab)
        {
            GUILayout.Space(2f);
            GUILayout.BeginHorizontal();
            {
                EditorGUILayout.PrefixLabel("Depth");

                int depth = mWidget.depth;
                if (GUILayout.Button("Back", GUILayout.Width(60f)))
                {
                    --depth;
                }
                depth = EditorGUILayout.IntField(depth);
                if (GUILayout.Button("Forward", GUILayout.Width(60f)))
                {
                    ++depth;
                }

                if (mWidget.depth != depth)
                {
                    NGUIEditorTools.RegisterUndo("Depth Change", mWidget);
                    mWidget.depth = depth;
                    mDepthCheck   = true;
                }
            }
            GUILayout.EndHorizontal();

            UIPanel panel = mWidget.panel;

            if (panel != null)
            {
                int matchingDepths    = 0;
                int matchingMaterials = 0;

                for (int i = 0; i < panel.widgets.size; ++i)
                {
                    UIWidget w = panel.widgets[i];

                    if (w != null && w.material == mWidget.material)
                    {
                        ++matchingMaterials;
                        if (w.depth == mWidget.depth)
                        {
                            ++matchingDepths;
                        }
                    }
                }

                if (matchingDepths > 1)
                {
                    EditorGUILayout.HelpBox(matchingDepths + " widgets are using the depth value of " + mWidget.depth +
                                            ". It may not be clear what should be in front of what.", MessageType.Warning);
                }
                else if (matchingMaterials < 2 && panel.widgets.size > 1)
                {
                    EditorGUILayout.HelpBox("This widget uses a unique material and doesn't get batched with any others. You will need to adjust its transform position's Z to determine what's in front of what.", MessageType.Warning);
                }

                if (mDepthCheck)
                {
                    if (panel.drawCalls.size > 1)
                    {
                        EditorGUILayout.HelpBox("The widgets underneath this panel are using more than one atlas. You may need to adjust transform position's Z value instead. When adjusting the Z, lower value means closer to the camera.", MessageType.Warning);
                    }
                }
            }
        }

        // Pixel-correctness
        if (type != PrefabType.Prefab)
        {
            GUILayout.BeginHorizontal();
            {
                EditorGUILayout.PrefixLabel("Correction");

                if (GUILayout.Button("Make Pixel-Perfect"))
                {
                    NGUIEditorTools.RegisterUndo("Make Pixel-Perfect", mWidget.transform);
                    mWidget.MakePixelPerfect();
                }
            }
            GUILayout.EndHorizontal();
        }

        EditorGUILayout.Space();

        // Color tint
        GUILayout.BeginHorizontal();
        Color color = EditorGUILayout.ColorField("Color Tint", mWidget.color);
        if (GUILayout.Button("Copy", GUILayout.Width(50f)))
        {
            NGUISettings.color = color;
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        NGUISettings.color = EditorGUILayout.ColorField("Clipboard", NGUISettings.color);
        if (GUILayout.Button("Paste", GUILayout.Width(50f)))
        {
            color = NGUISettings.color;
        }
        GUILayout.EndHorizontal();

        if (mWidget.color != color)
        {
            NGUIEditorTools.RegisterUndo("Color Change", mWidget);
            mWidget.color = color;
        }
    }
Ejemplo n.º 33
0
    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(130f);

        GUILayout.Space(3f);
        serializedObject.Update();

        SerializedProperty sppv = serializedObject.FindProperty("contentPivot");

        UIWidget.Pivot before = (UIWidget.Pivot)sppv.intValue;

        NGUIEditorTools.DrawProperty("Content Origin", sppv, false);

        SerializedProperty sp = NGUIEditorTools.DrawProperty("Movement", serializedObject, "movement");

        if (((UIScrollView.Movement)sp.intValue) == UIScrollView.Movement.Custom)
        {
            NGUIEditorTools.SetLabelWidth(20f);

            GUILayout.BeginHorizontal();
            GUILayout.Space(114f);
            NGUIEditorTools.DrawProperty("X", serializedObject, "customMovement.x", GUILayout.MinWidth(20f));
            NGUIEditorTools.DrawProperty("Y", serializedObject, "customMovement.y", GUILayout.MinWidth(20f));
            GUILayout.EndHorizontal();
        }

        NGUIEditorTools.SetLabelWidth(130f);

        NGUIEditorTools.DrawProperty("Drag Effect", serializedObject, "dragEffect");
        NGUIEditorTools.DrawProperty("Scroll Wheel Factor", serializedObject, "scrollWheelFactor");
        NGUIEditorTools.DrawProperty("Momentum Amount", serializedObject, "momentumAmount");

        NGUIEditorTools.DrawProperty("Restrict Within Panel", serializedObject, "restrictWithinPanel");
        NGUIEditorTools.DrawProperty("Cancel Drag If Fits", serializedObject, "disableDragIfFits");
        NGUIEditorTools.DrawProperty("Smooth Drag Start", serializedObject, "smoothDragStart");
        NGUIEditorTools.DrawProperty("IOS Drag Emulation", serializedObject, "iOSDragEmulation");

        NGUIEditorTools.SetLabelWidth(100f);

        if (NGUIEditorTools.DrawHeader("Scroll Bars"))
        {
            NGUIEditorTools.BeginContents();
            NGUIEditorTools.DrawProperty("Horizontal", serializedObject, "horizontalScrollBar");
            NGUIEditorTools.DrawProperty("Vertical", serializedObject, "verticalScrollBar");
            NGUIEditorTools.DrawProperty("page", serializedObject, "PageBar");
            NGUIEditorTools.DrawProperty("Show Condition", serializedObject, "showScrollBars");

            NGUIEditorTools.DrawProperty("Darg Begin", serializedObject, "DargBegin");
            NGUIEditorTools.DrawProperty("Darg End", serializedObject, "DargEnd");
            NGUIEditorTools.DrawProperty("Undarg Begin", serializedObject, "UndargBegin");
            NGUIEditorTools.DrawProperty("UndargEnd", serializedObject, "UndargEnd");

            NGUIEditorTools.EndContents();
        }

        NGUIEditorTools.DrawProperty("This Grid", serializedObject, "thisGrid");
        serializedObject.ApplyModifiedProperties();

        if (before != (UIWidget.Pivot)sppv.intValue)
        {
            (target as UIScrollView).ResetPosition();
        }
    }
Ejemplo n.º 34
0
    /// <summary>
    /// Draw the on-screen selection, knobs, and handle all interaction logic.
    /// </summary>

    public void OnSceneGUI()
    {
        if (!UIWidget.showHandles)
        {
            return;
        }

        mWidget = target as UIWidget;

        Handles.color = mOutlineColor;
        Transform t = mWidget.cachedTransform;

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

        Vector3[] corners = NGUIMath.CalculateWidgetCorners(mWidget);
        Handles.DrawLine(corners[0], corners[1]);
        Handles.DrawLine(corners[1], corners[2]);
        Handles.DrawLine(corners[2], corners[3]);
        Handles.DrawLine(corners[0], corners[3]);

        Vector3[] worldPos = new Vector3[8];

        worldPos[0] = corners[0];
        worldPos[1] = corners[1];
        worldPos[2] = corners[2];
        worldPos[3] = corners[3];

        worldPos[4] = (corners[0] + corners[1]) * 0.5f;
        worldPos[5] = (corners[1] + corners[2]) * 0.5f;
        worldPos[6] = (corners[2] + corners[3]) * 0.5f;
        worldPos[7] = (corners[0] + corners[3]) * 0.5f;

        Vector2[] screenPos = new Vector2[8];
        for (int i = 0; i < 8; ++i)
        {
            screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);
        }

        Bounds b = new Bounds(screenPos[0], Vector3.zero);

        for (int i = 1; i < 8; ++i)
        {
            b.Encapsulate(screenPos[i]);
        }

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

        UIWidget.Pivot pivotUnderMouse = UIWidget.Pivot.Center;

        if (actionUnderMouse == Action.None)
        {
            int   index = 0;
            float dist  = GetScreenDistance(worldPos, e.mousePosition, out index);

            if (mWidget.showResizeHandles && dist < 10f)
            {
                pivotUnderMouse  = mPivots[index];
                actionUnderMouse = Action.Scale;
            }
            else if (e.modifiers == 0 && SceneViewDistanceToRectangle(corners, e.mousePosition) == 0f)
            {
                actionUnderMouse = Action.Move;
            }
            else if (dist < 30f)
            {
                actionUnderMouse = Action.Rotate;
            }
        }

        // Change the mouse cursor to a more appropriate one
#if !UNITY_3_5
        {
            Vector2 min = b.min;
            Vector2 max = b.max;

            min.x -= 30f;
            max.x += 30f;
            min.y -= 30f;
            max.y += 30f;

            Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);

            if (actionUnderMouse == Action.Rotate)
            {
                SetCursorRect(rect, MouseCursor.RotateArrow);
            }
            else if (actionUnderMouse == Action.Move)
            {
                SetCursorRect(rect, MouseCursor.MoveArrow);
            }
            else if (mWidget.showResizeHandles && actionUnderMouse == Action.Scale)
            {
                SetCursorRect(rect, MouseCursor.ScaleArrow);
            }
            else
            {
                SetCursorRect(rect, MouseCursor.Arrow);
            }
        }
#endif

        switch (type)
        {
        case EventType.Repaint:
        {
            if (mWidget.showResizeHandles)
            {
                Handles.BeginGUI();
                {
                    for (int i = 0; i < 8; ++i)
                    {
                        DrawKnob(worldPos[i], mWidget.pivot == mPivots[i], id);
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            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(corners, out mStartDrag))
            {
                mStartPos             = t.position;
                mStartRot             = t.localRotation.eulerAngles;
                mStartDir             = mStartDrag - t.position;
                mStartScale           = t.localScale;
                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(corners, 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)
                                {
                                    mStartPos = t.position;
                                    NGUIEditorTools.RegisterUndo("Move widget", t);
                                }
                                else if (mActionUnderMouse == Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                    NGUIEditorTools.RegisterUndo("Rotate widget", t);
                                }
                                else if (mActionUnderMouse == Action.Scale)
                                {
                                    mStartPos   = t.localPosition;
                                    mStartScale = t.localScale;
                                    mDragPivot  = pivotUnderMouse;
                                    NGUIEditorTools.RegisterUndo("Scale widget", t);
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != Action.None)
                        {
                            if (mAction == Action.Move)
                            {
                                t.position      = mStartPos + (pos - mStartDrag);
                                pos             = t.localPosition;
                                pos.x           = Mathf.RoundToInt(pos.x);
                                pos.y           = Mathf.RoundToInt(pos.y);
                                t.localPosition = pos;
                            }
                            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;
                                    if (e.modifiers != EventModifiers.Shift)
                                    {
                                        angle = Mathf.Round(angle / 15f) * 15f;
                                    }
                                    else
                                    {
                                        angle = Mathf.Round(angle);
                                    }
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == 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
                                AdjustPosAndScale(mWidget, mStartPos, mStartScale, delta, mDragPivot);
                            }
                        }
                    }
                }
            }
        }
        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: Select the widget below
                        SelectWidget(mWidget, e.mousePosition, false);
                        handled = true;
                    }
                    else if (mAction == Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the widget above
                            SelectWidget(mWidget, e.mousePosition, true);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        mAction           = Action.None;
                        mActionUnderMouse = Action.None;
                        Vector3 pos   = t.localPosition;
                        Vector3 scale = t.localScale;

                        if (mWidget.pixelPerfectAfterResize)
                        {
                            t.localPosition = pos;
                            t.localScale    = scale;

                            mWidget.MakePixelPerfect();
                        }
                        else
                        {
                            pos.x   = Mathf.Round(pos.x);
                            pos.y   = Mathf.Round(pos.y);
                            scale.x = Mathf.Round(scale.x);
                            scale.y = Mathf.Round(scale.y);

                            t.localPosition = pos;
                            t.localScale    = scale;
                        }
                        handled = true;
                    }

                    if (handled)
                    {
                        mActionUnderMouse = Action.None;
                        mAction           = Action.None;
                        e.Use();
                    }
                }
            }
            else if (mAllowSelection)
            {
                BetterList <UIWidget> widgets = SceneViewRaycast(mWidget.panel, e.mousePosition);
                if (widgets.size > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                Vector3 pos = t.localPosition;
                pos.y          += 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                Vector3 pos = t.localPosition;
                pos.y          -= 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                Vector3 pos = t.localPosition;
                pos.x          -= 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                Vector3 pos = t.localPosition;
                pos.x          += 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != Action.None)
                    {
                        if (mAction == Action.Move)
                        {
                            t.position = mStartPos;
                        }
                        else if (mAction == Action.Rotate)
                        {
                            t.localRotation = Quaternion.Euler(mStartRot);
                        }
                        else if (mAction == Action.Scale)
                        {
                            t.position   = mStartPos;
                            t.localScale = mStartScale;
                        }
                    }

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

                    mActionUnderMouse = Action.None;
                    mAction           = Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Ejemplo n.º 35
0
    /// <summary>
    /// Draw the on-screen selection, knobs, and handle all interaction logic.
    /// </summary>

    public void OnSceneGUI()
    {
        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);

                                // Snap the widget
                                Vector3 after = NGUISnap.Snap(t.localPosition, 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)
            {
                BetterList <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.size > 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;
        }
    }
Ejemplo n.º 36
0
    /// <summary>
    /// Adjust the transform's position and scale.
    /// </summary>

    static void AdjustPosAndScale(UIWidget w, Vector3 startLocalPos, Vector3 startLocalScale, Vector3 worldDelta, UIWidget.Pivot dragPivot)
    {
        Transform  t             = w.cachedTransform;
        Transform  parent        = t.parent;
        Matrix4x4  parentToLocal = (parent != null) ? t.parent.worldToLocalMatrix : Matrix4x4.identity;
        Matrix4x4  worldToLocal  = parentToLocal;
        Quaternion invRot        = Quaternion.Inverse(t.localRotation);

        worldToLocal = worldToLocal * Matrix4x4.TRS(Vector3.zero, invRot, Vector3.one);
        Vector3 localDelta = worldToLocal.MultiplyVector(worldDelta);

        bool  canBeSquare = false;
        float left        = 0f;
        float right       = 0f;
        float top         = 0f;
        float bottom      = 0f;

        switch (dragPivot)
        {
        case UIWidget.Pivot.TopLeft:
            canBeSquare = (w.pivot == UIWidget.Pivot.BottomRight);
            left        = localDelta.x;
            top         = localDelta.y;
            break;

        case UIWidget.Pivot.Left:
            left = localDelta.x;
            break;

        case UIWidget.Pivot.BottomLeft:
            canBeSquare = (w.pivot == UIWidget.Pivot.TopRight);
            left        = localDelta.x;
            bottom      = localDelta.y;
            break;

        case UIWidget.Pivot.Top:
            top = localDelta.y;
            break;

        case UIWidget.Pivot.Bottom:
            bottom = localDelta.y;
            break;

        case UIWidget.Pivot.TopRight:
            canBeSquare = (w.pivot == UIWidget.Pivot.BottomLeft);
            right       = localDelta.x;
            top         = localDelta.y;
            break;

        case UIWidget.Pivot.Right:
            right = localDelta.x;
            break;

        case UIWidget.Pivot.BottomRight:
            canBeSquare = (w.pivot == UIWidget.Pivot.TopLeft);
            right       = localDelta.x;
            bottom      = localDelta.y;
            break;
        }

        AdjustWidget(w, startLocalPos, startLocalScale, left, top, right, bottom, canBeSquare && Event.current.modifiers == EventModifiers.Shift);
    }
Ejemplo n.º 37
0
 static bool IsLeft(UIWidget.Pivot pivot)
 {
     return(pivot == UIWidget.Pivot.Left ||
            pivot == UIWidget.Pivot.TopLeft ||
            pivot == UIWidget.Pivot.BottomLeft);
 }
Ejemplo n.º 38
0
    /// <summary>
    /// Draw the on-screen selection, knobs, and handle all interaction logic.
    /// </summary>
    public void OnSceneGUI()
    {
        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);

        Vector3[] corners = mWidget.worldCorners;

        Handles.color = handlesColor;
        Handles.DrawLine(corners[0], corners[1]);
        Handles.DrawLine(corners[1], corners[2]);
        Handles.DrawLine(corners[2], corners[3]);
        Handles.DrawLine(corners[0], corners[3]);

        Vector3[] worldPos = new Vector3[8];

        worldPos[0] = corners[0];
        worldPos[1] = corners[1];
        worldPos[2] = corners[2];
        worldPos[3] = corners[3];

        worldPos[4] = (corners[0] + corners[1]) * 0.5f;
        worldPos[5] = (corners[1] + corners[2]) * 0.5f;
        worldPos[6] = (corners[2] + corners[3]) * 0.5f;
        worldPos[7] = (corners[0] + corners[3]) * 0.5f;

        // Time to figure out what kind of action is underneath the mouse
        Action actionUnderMouse = mAction;
        UIWidget.Pivot pivotUnderMouse = UIWidget.Pivot.Center;

        if (actionUnderMouse == Action.None)
        {
            int index = 0;
            float dist = GetScreenDistance(worldPos, e.mousePosition, out index);

            if (mWidget.canResize && dist < 10f)
            {
                pivotUnderMouse = mPivots[index];
                actionUnderMouse = Action.Scale;
            }
            else if (e.modifiers == 0 && NGUIEditorTools.SceneViewDistanceToRectangle(corners, e.mousePosition) == 0f)
            {
                actionUnderMouse = Action.Move;
            }
            else if (dist < 30f)
            {
                actionUnderMouse = Action.Rotate;
            }
        }

        // Change the mouse cursor to a more appropriate one
        #if !UNITY_3_5
        {
            Vector2[] screenPos = new Vector2[8];
            for (int i = 0; i < 8; ++i) screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);

            Bounds b = new Bounds(screenPos[0], Vector3.zero);
            for (int i = 1; i < 8; ++i) b.Encapsulate(screenPos[i]);

            Vector2 min = b.min;
            Vector2 max = b.max;

            min.x -= 30f;
            max.x += 30f;
            min.y -= 30f;
            max.y += 30f;

            Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);

            if (actionUnderMouse == Action.Rotate)
            {
                SetCursorRect(rect, MouseCursor.RotateArrow);
            }
            else if (actionUnderMouse == Action.Move)
            {
                SetCursorRect(rect, MouseCursor.MoveArrow);
            }
            else if (actionUnderMouse == Action.Scale)
            {
                SetCursorRect(rect, MouseCursor.ScaleArrow);
            }
            else SetCursorRect(rect, MouseCursor.Arrow);
        }
        #endif

        switch (type)
        {
            case EventType.Repaint:
            {
                Handles.BeginGUI();
                {
                    for (int i = 0; i < 8; ++i)
                    {
                        DrawKnob(worldPos[i], mWidget.pivot == mPivots[i], mWidget.canResize, id);
                    }
                }
                Handles.EndGUI();
            }
            break;

            case EventType.MouseDown:
            {
                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(corners, out mStartDrag))
                {
                    mStartPos = t.position;
                    mStartRot = t.localRotation.eulerAngles;
                    mStartDir = mStartDrag - t.position;
                    mStartWidth = mWidget.width;
                    mStartHeight = mWidget.height;
                    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(corners, 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)
                                    {
                                        mStartPos = t.position;
                                        NGUIEditorTools.RegisterUndo("Move widget", t);
                                    }
                                    else if (mActionUnderMouse == Action.Rotate)
                                    {
                                        mStartRot = t.localRotation.eulerAngles;
                                        mStartDir = mStartDrag - t.position;
                                        NGUIEditorTools.RegisterUndo("Rotate widget", t);
                                    }
                                    else if (mActionUnderMouse == Action.Scale)
                                    {
                                        mStartPos = t.localPosition;
                                        mStartWidth = mWidget.width;
                                        mStartHeight = mWidget.height;
                                        mDragPivot = pivotUnderMouse;
                                        NGUIEditorTools.RegisterUndo("Scale widget", t);
                                        NGUIEditorTools.RegisterUndo("Scale widget", mWidget);
                                    }
                                    mAction = actionUnderMouse;
                                }
                            }

                            if (mAction != Action.None)
                            {
                                if (mAction == Action.Move)
                                {
                                    t.position = mStartPos + (pos - mStartDrag);
                                    pos = t.localPosition;
                                    pos.x = Mathf.Round(pos.x);
                                    pos.y = Mathf.Round(pos.y);
                                    pos.z = Mathf.Round(pos.z);
                                    t.localPosition = pos;
                                }
                                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;
                                        if (e.modifiers != EventModifiers.Shift) angle = Mathf.Round(angle / 15f) * 15f;
                                        else angle = Mathf.Round(angle);
                                        t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                    }
                                }
                                else if (mAction == 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
                                    AdjustPosAndScale(mWidget, mStartPos, mStartWidth, mStartHeight, delta, mDragPivot);
                                }
                            }
                        }
                    }
                }
            }
            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: Select the widget below
                            NGUIEditorTools.SelectWidgetOrContainer(mWidget.gameObject, e.mousePosition, false);
                            handled = true;
                        }
                        else if (mAction == Action.None)
                        {
                            if (mAllowSelection)
                            {
                                // Left-click: Select the widget above
                                NGUIEditorTools.SelectWidgetOrContainer(mWidget.gameObject, e.mousePosition, true);
                                handled = true;
                            }
                        }
                        else
                        {
                            // Finished dragging something
                            mAction = Action.None;
                            mActionUnderMouse = Action.None;
                            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)
                        {
                            mActionUnderMouse = Action.None;
                            mAction = Action.None;
                            e.Use();
                        }
                    }
                }
                else if (mAllowSelection)
                {
                    BetterList<UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                    if (widgets.size > 0) Selection.activeGameObject = widgets[0].gameObject;
                }
                mAllowSelection = true;
            }
            break;

            case EventType.KeyDown:
            {
                if (e.keyCode == KeyCode.UpArrow)
                {
                    Vector3 pos = t.localPosition;
                    pos.y += 1f;
                    t.localPosition = pos;
                    e.Use();
                }
                else if (e.keyCode == KeyCode.DownArrow)
                {
                    Vector3 pos = t.localPosition;
                    pos.y -= 1f;
                    t.localPosition = pos;
                    e.Use();
                }
                else if (e.keyCode == KeyCode.LeftArrow)
                {
                    Vector3 pos = t.localPosition;
                    pos.x -= 1f;
                    t.localPosition = pos;
                    e.Use();
                }
                else if (e.keyCode == KeyCode.RightArrow)
                {
                    Vector3 pos = t.localPosition;
                    pos.x += 1f;
                    t.localPosition = pos;
                    e.Use();
                }
                else if (e.keyCode == KeyCode.Escape)
                {
                    if (GUIUtility.hotControl == id)
                    {
                        if (mAction != Action.None)
                        {
                            if (mAction == Action.Move)
                            {
                                t.position = mStartPos;
                            }
                            else if (mAction == Action.Rotate)
                            {
                                t.localRotation = Quaternion.Euler(mStartRot);
                            }
                            else if (mAction == Action.Scale)
                            {
                                t.position = mStartPos;
                                mWidget.width = mStartWidth;
                                mWidget.height = mStartHeight;
                            }
                        }

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

                        mActionUnderMouse = Action.None;
                        mAction = Action.None;
                        e.Use();
                    }
                    else Selection.activeGameObject = null;
                }
            }
            break;
        }
    }
Ejemplo n.º 39
0
 static bool IsTop(UIWidget.Pivot pivot)
 {
     return(pivot == UIWidget.Pivot.Top ||
            pivot == UIWidget.Pivot.TopLeft ||
            pivot == UIWidget.Pivot.TopRight);
 }
Ejemplo n.º 40
0
	/// <summary>
	/// Handles & interaction.
	/// </summary>

	public void OnSceneGUI ()
	{
		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;
		}
	}
Ejemplo n.º 41
0
    /// <summary>
    /// Adjust the widget's rectangle based on the specified modifier values.
    /// </summary>

    static void AdjustWidget(UIWidget w, Vector3 pos, Vector3 scale, float left, float top, float right, float bottom, bool makeSquare)
    {
        Vector2 offset  = w.pivotOffset;
        Vector4 padding = w.relativePadding;
        Vector2 size    = w.relativeSize;

        offset.x -= padding.x;
        offset.y -= padding.y;
        size.x   += padding.x + padding.z;
        size.y   += padding.y + padding.w;

        scale.Scale(size);

        offset.y = -offset.y;

        Transform  t   = w.cachedTransform;
        Quaternion rot = t.localRotation;

        UIWidget.Pivot pivot = w.pivot;

        Vector2 rotatedTL = new Vector2(left, top);
        Vector2 rotatedTR = new Vector2(right, top);
        Vector2 rotatedBL = new Vector2(left, bottom);
        Vector2 rotatedBR = new Vector2(right, bottom);
        Vector2 rotatedL  = new Vector2(left, 0f);
        Vector2 rotatedR  = new Vector2(right, 0f);
        Vector2 rotatedT  = new Vector2(0f, top);
        Vector2 rotatedB  = new Vector2(0f, bottom);

        rotatedTL = rot * rotatedTL;
        rotatedTR = rot * rotatedTR;
        rotatedBL = rot * rotatedBL;
        rotatedBR = rot * rotatedBR;
        rotatedL  = rot * rotatedL;
        rotatedR  = rot * rotatedR;
        rotatedT  = rot * rotatedT;
        rotatedB  = rot * rotatedB;

        switch (pivot)
        {
        case UIWidget.Pivot.TopLeft:
            pos.x += rotatedTL.x;
            pos.y += rotatedTL.y;
            break;

        case UIWidget.Pivot.BottomRight:
            pos.x += rotatedBR.x;
            pos.y += rotatedBR.y;
            break;

        case UIWidget.Pivot.BottomLeft:
            pos.x += rotatedBL.x;
            pos.y += rotatedBL.y;
            break;

        case UIWidget.Pivot.TopRight:
            pos.x += rotatedTR.x;
            pos.y += rotatedTR.y;
            break;

        case UIWidget.Pivot.Left:
            pos.x += rotatedL.x + (rotatedT.x + rotatedB.x) * 0.5f;
            pos.y += rotatedL.y + (rotatedT.y + rotatedB.y) * 0.5f;
            break;

        case UIWidget.Pivot.Right:
            pos.x += rotatedR.x + (rotatedT.x + rotatedB.x) * 0.5f;
            pos.y += rotatedR.y + (rotatedT.y + rotatedB.y) * 0.5f;
            break;

        case UIWidget.Pivot.Top:
            pos.x += rotatedT.x + (rotatedL.x + rotatedR.x) * 0.5f;
            pos.y += rotatedT.y + (rotatedL.y + rotatedR.y) * 0.5f;
            break;

        case UIWidget.Pivot.Bottom:
            pos.x += rotatedB.x + (rotatedL.x + rotatedR.x) * 0.5f;
            pos.y += rotatedB.y + (rotatedL.y + rotatedR.y) * 0.5f;
            break;

        case UIWidget.Pivot.Center:
            pos.x += (rotatedL.x + rotatedR.x + rotatedT.x + rotatedB.x) * 0.5f;
            pos.y += (rotatedT.y + rotatedB.y + rotatedL.y + rotatedR.y) * 0.5f;
            break;
        }

        scale.x -= left - right;
        scale.y += top - bottom;

        scale.x /= size.x;
        scale.y /= size.y;

        Vector4 border = w.border;
        float   minx   = Mathf.Max(2f, padding.x + padding.z + border.x + border.z);
        float   miny   = Mathf.Max(2f, padding.y + padding.w + border.y + border.w);

        if (scale.x < minx)
        {
            scale.x = minx;
        }
        if (scale.y < miny)
        {
            scale.y = miny;
        }

        // NOTE: This will only work correctly when dragging the corner opposite of the pivot point
        if (makeSquare)
        {
            scale.x = Mathf.Min(scale.x, scale.y);
            scale.y = scale.x;
        }

        t.localPosition = pos;
        t.localScale    = scale;
    }
Ejemplo n.º 42
0
    /// <summary>
    /// Draw the on-screen selection, knobs, and handle all interaction logic.
    /// Lets the Editor handle an event in the scene view.
    /// </summary>
    public void OnSceneGUI()
    {
        //Tools.current = Tool.View;

        mWidget = target as UIWidget;

        Handles.color = mOutlineColor;
        Transform t = mWidget.cachedTransform;

        Event e = Event.current;
        int id = GUIUtility.GetControlID(s_Hash, FocusType.Passive);//此GUI控件,不会有键盘聚焦事件
        EventType type = e.GetTypeForControl(id);

        //绘制控件的四条边
        Vector3[] corners = NGUIMath.CalculateWidgetCorners(mWidget);
        Handles.DrawLine(corners[0], corners[1]);
        Handles.DrawLine(corners[1], corners[2]);
        Handles.DrawLine(corners[2], corners[3]);
        Handles.DrawLine(corners[0], corners[3]);

        Vector3[] worldPos = new Vector3[8];

        worldPos[0] = corners[0];
        worldPos[1] = corners[1];
        worldPos[2] = corners[2];
        worldPos[3] = corners[3];

        worldPos[4] = (corners[0] + corners[1]) * 0.5f;
        worldPos[5] = (corners[1] + corners[2]) * 0.5f;
        worldPos[6] = (corners[2] + corners[3]) * 0.5f;
        worldPos[7] = (corners[0] + corners[3]) * 0.5f;

        Vector2[] screenPos = new Vector2[8];
        for (int i = 0; i < 8; ++i) screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);

        //Represents an axis aligned bounding box.这个box与坐标轴平行,不会因target而rotate
        //Vector3.zero 表示这个Bounds的Size为(0,0,0)
        Bounds b = new Bounds(screenPos[0], Vector3.zero);
        //Grow the bounds to encapsulate the bounds.慢慢将各点纳入bounds
        for (int i = 1; i < 8; ++i) b.Encapsulate(screenPos[i]);

        // Time to figure out what kind of action is underneath the mouse
        Action actionUnderMouse = mAction;
        UIWidget.Pivot pivotUnderMouse = UIWidget.Pivot.Center;

        if (actionUnderMouse == Action.None)
        {
            int index = 0;
            float dist = GetScreenDistance(worldPos, e.mousePosition, out index);

            //缩放
            if (dist < 10f)
            {
                pivotUnderMouse = mPivots[index];
                actionUnderMouse = Action.Scale;
            }
            //移动,modifier【调节器;<语>修饰语】这里表示组合键,比如旋转的alt键
            else if (e.modifiers == 0 && NGUIEditorTools.DistanceToRectangle(corners, e.mousePosition) == 0f)
            {
                if (Tools.current != Tool.Rotate && Tools.current != Tool.Scale)
                {
                    actionUnderMouse = Action.Move;
                }
            }
            //旋转
            else if (dist < 30f)
            {
                actionUnderMouse = Action.Rotate;
            }
        }

        // Change the mouse cursor to a more appropriate one
        #if !UNITY_3_5
        {
            Vector2 min = b.min;
            Vector2 max = b.max;

            min.x -= 30f;
            max.x += 30f;
            min.y -= 30f;
            max.y += 30f;

            Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);

            if (actionUnderMouse == Action.Rotate)
            {
                SetCursorRect(rect, MouseCursor.RotateArrow);
            }
            else if (actionUnderMouse == Action.Move)
            {
                SetCursorRect(rect, MouseCursor.MoveArrow);
            }
            else if (actionUnderMouse == Action.Scale)
            {
                SetCursorRect(rect, MouseCursor.ScaleArrow);
            }
            else SetCursorRect(rect, MouseCursor.Arrow);
        }
        #endif

        switch (type)
        {
            case EventType.Repaint:
            {
                Handles.BeginGUI();
                {
                    for (int i = 0; i < 8; ++i)
                    {
                        DrawKnob(worldPos[i], mWidget.pivot == mPivots[i], id);
                    }
                }
                Handles.EndGUI();
            }
            break;

            case EventType.MouseDown:
            {
                mStartMouse = e.mousePosition;
                mAllowSelection = true;

                if (e.button == 1)
                {
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
                else if (e.button == 0 && actionUnderMouse != Action.None && Raycast(corners, out mStartDrag))
                {
                    mStartPos = t.position;
                    mStartRot = t.localRotation.eulerAngles;
                    mStartDir = mStartDrag - t.position;
                    mStartScale = t.localScale;
                    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(corners, 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)
                                    {
                                        mStartPos = t.position;
                                        NGUIEditorTools.RegisterUndo("Move widget", t);
                                    }
                                    else if (mActionUnderMouse == Action.Rotate)
                                    {
                                        mStartRot = t.localRotation.eulerAngles;
                                        mStartDir = mStartDrag - t.position;
                                        NGUIEditorTools.RegisterUndo("Rotate widget", t);
                                    }
                                    else if (mActionUnderMouse == Action.Scale)
                                    {
                                        mStartPos = t.localPosition;
                                        mStartScale = t.localScale;
                                        mDragPivot = pivotUnderMouse;
                                        NGUIEditorTools.RegisterUndo("Scale widget", t);
                                    }
                                    mAction = actionUnderMouse;
                                }
                            }

                            if (mAction != Action.None)
                            {
                                if (mAction == Action.Move)
                                {
                                    t.position = mStartPos + (pos - mStartDrag);
                                    pos = t.localPosition;
                                    pos.x = Mathf.RoundToInt(pos.x);
                                    pos.y = Mathf.RoundToInt(pos.y);
                                    t.localPosition = pos;
                                }
                                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;
                                        if (e.modifiers != EventModifiers.Shift) angle = Mathf.Round(angle / 15f) * 15f;
                                        else angle = Mathf.Round(angle);
                                        t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                    }
                                }
                                else if (mAction == 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
                                    AdjustPosAndScale(mWidget, mStartPos, mStartScale, delta, mDragPivot);
                                }
                            }
                        }
                    }
                }
            }
            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)
                        {
                            //为了规避与系统的左键选择,NGUI采用右键选择的方式。
                            //这里是选择比当前对象更深一层的对象
                            // Right-click: Select the widget below
                            UIWidget last = null;
                            UIWidget[] widgets = Raycast(mWidget, e.mousePosition);

                            for (int i = widgets.Length; i > 0; )
                            {
                                UIWidget w = widgets[--i];
                                if (w == mWidget) break;
                                last = w;
                            }

                            if (last != null)
                            {
                                Selection.activeGameObject = last.gameObject;
                                handled = true;
                            }
                        }
                        else if (mAction == Action.None)
                        {
                            if (mAllowSelection)
                            {
                                // 选择比当前对象更上一层的对象,用于层次选择
                                // Left-click: Select the widget above
                                UIWidget last = null;
                                UIWidget[] widgets = Raycast(mWidget, e.mousePosition);

                                if (widgets.Length > 0)
                                {
                                    for (int i = 0; i < widgets.Length; ++i)
                                    {
                                        UIWidget w = widgets[i];

                                        if (w == mWidget)
                                        {
                                            if (last != null) Selection.activeGameObject = last.gameObject;
                                            handled = true;
                                            break;
                                        }
                                        last = w;
                                    }

                                    if (!handled)
                                    {
                                        Selection.activeGameObject = widgets[0].gameObject;
                                        handled = true;
                                    }
                                }
                            }
                        }
                        else
                        {
                            // Finished dragging something
                            mAction = Action.None;
                            mActionUnderMouse = Action.None;
                            Vector3 pos = t.localPosition;
                            Vector3 scale = t.localScale;

                            if (mWidget.pixelPerfectAfterResize)
                            {
                                t.localPosition = pos;
                                t.localScale = scale;

                                mWidget.MakePixelPerfect();
                            }
                            else
                            {
                                pos.x = Mathf.Round(pos.x);
                                pos.y = Mathf.Round(pos.y);
                                scale.x = Mathf.Round(scale.x);
                                scale.y = Mathf.Round(scale.y);

                                t.localPosition = pos;
                                t.localScale = scale;
                            }
                            handled = true;
                        }

                        if (handled)
                        {
                            mActionUnderMouse = Action.None;
                            mAction = Action.None;
                            e.Use();
                        }
                    }
                }
                else if (mAllowSelection)
                {
                    UIWidget[] widgets = Raycast(mWidget, e.mousePosition);
                    if (widgets.Length > 0) Selection.activeGameObject = widgets[0].gameObject;
                }
                mAllowSelection = true;
            }
            break;

            case EventType.KeyDown:
            {
                if (e.keyCode == KeyCode.UpArrow)
                {
                    Vector3 pos = t.localPosition;
                    pos.y += 1f;
                    t.localPosition = pos;
                    e.Use();
                }
                else if (e.keyCode == KeyCode.DownArrow)
                {
                    Vector3 pos = t.localPosition;
                    pos.y -= 1f;
                    t.localPosition = pos;
                    e.Use();
                }
                else if (e.keyCode == KeyCode.LeftArrow)
                {
                    Vector3 pos = t.localPosition;
                    pos.x -= 1f;
                    t.localPosition = pos;
                    e.Use();
                }
                else if (e.keyCode == KeyCode.RightArrow)
                {
                    Vector3 pos = t.localPosition;
                    pos.x += 1f;
                    t.localPosition = pos;
                    e.Use();
                }
                else if (e.keyCode == KeyCode.Escape)
                {
                    if (GUIUtility.hotControl == id)
                    {
                        if (mAction != Action.None)
                        {
                            if (mAction == Action.Move)
                            {
                                t.position = mStartPos;
                            }
                            else if (mAction == Action.Rotate)
                            {
                                t.localRotation = Quaternion.Euler(mStartRot);
                            }
                            else if (mAction == Action.Scale)
                            {
                                t.position = mStartPos;
                                t.localScale = mStartScale;
                            }
                        }

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

                        mActionUnderMouse = Action.None;
                        mAction = Action.None;
                        e.Use();
                    }
                    else
                    {
                        Selection.activeGameObject = null;
                        Tools.current = Tool.Move;
                    }
                }
            }
            break;
        }
    }
Ejemplo n.º 43
0
	/// <summary>
	/// Draw the on-screen selection, knobs, and handle all interaction logic.
	/// </summary>

	public void OnSceneGUI ()
	{
		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);

									// Snap the widget
									Vector3 after = NGUISnap.Snap(t.localPosition, 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 (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)
				{
					BetterList<UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
					if (widgets.size > 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;
		}
	}
Ejemplo n.º 44
0
    /// <summary>
    /// All widgets have depth, color and make pixel-perfect options
    /// </summary>

    protected void DrawCommonProperties()
    {
        PrefabType type = PrefabUtility.GetPrefabType(mWidget.gameObject);

        NGUIEditorTools.DrawSeparator();

#if UNITY_3_5
        // Pivot point -- old school drop-down style
        UIWidget.Pivot pivot = (UIWidget.Pivot)EditorGUILayout.EnumPopup("Pivot", mWidget.pivot);

        if (mWidget.pivot != pivot)
        {
            NGUIEditorTools.RegisterUndo("Pivot Change", mWidget);
            mWidget.pivot = pivot;
        }
#else
        // Pivot point -- the new, more visual style
        GUILayout.BeginHorizontal();
        GUILayout.Label("Pivot", GUILayout.Width(76f));
        Toggle("\u25C4", "ButtonLeft", UIWidget.Pivot.Left, true);
        Toggle("\u25AC", "ButtonMid", UIWidget.Pivot.Center, true);
        Toggle("\u25BA", "ButtonRight", UIWidget.Pivot.Right, true);
        Toggle("\u25B2", "ButtonLeft", UIWidget.Pivot.Top, false);
        Toggle("\u258C", "ButtonMid", UIWidget.Pivot.Center, false);
        Toggle("\u25BC", "ButtonRight", UIWidget.Pivot.Bottom, false);
        GUILayout.EndHorizontal();
#endif

        // Depth navigation
        if (type != PrefabType.Prefab)
        {
            GUILayout.Space(2f);
            GUILayout.BeginHorizontal();
            {
                EditorGUILayout.PrefixLabel("Depth");

                int depth = mWidget.depth;
                if (GUILayout.Button("Back", GUILayout.Width(60f)))
                {
                    --depth;
                }
                depth = EditorGUILayout.IntField(depth);
                if (GUILayout.Button("Forward", GUILayout.Width(60f)))
                {
                    ++depth;
                }

                if (mWidget.depth != depth)
                {
                    NGUIEditorTools.RegisterUndo("Depth Change", mWidget);
                    mWidget.depth = depth;
                }
            }
            GUILayout.EndHorizontal();

            int matchingDepths = 0;

            for (int i = 0; i < UIWidget.list.size; ++i)
            {
                UIWidget w = UIWidget.list[i];
                if (w != null && w.depth == mWidget.depth)
                {
                    ++matchingDepths;
                }
            }

            if (matchingDepths > 1)
            {
                EditorGUILayout.HelpBox(matchingDepths + " widgets are using the depth value of " + mWidget.depth +
                                        ". It may not be clear what should be in front of what.", MessageType.Warning);
            }
        }

        // Pixel-correctness
        if (type != PrefabType.Prefab)
        {
            GUILayout.BeginHorizontal();
            {
                EditorGUILayout.PrefixLabel("Correction");

                if (GUILayout.Button("Make Pixel-Perfect"))
                {
                    NGUIEditorTools.RegisterUndo("Make Pixel-Perfect", mWidget.transform);
                    mWidget.MakePixelPerfect();
                }
            }
            GUILayout.EndHorizontal();
        }

        EditorGUILayout.Space();

        // Color tint
        GUILayout.BeginHorizontal();
        Color color = EditorGUILayout.ColorField("Color Tint", mWidget.color);
        if (GUILayout.Button("Copy", GUILayout.Width(50f)))
        {
            NGUISettings.color = color;
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        NGUISettings.color = EditorGUILayout.ColorField("Clipboard", NGUISettings.color);
        if (GUILayout.Button("Paste", GUILayout.Width(50f)))
        {
            color = NGUISettings.color;
        }
        GUILayout.EndHorizontal();

        if (mWidget.color != color)
        {
            NGUIEditorTools.RegisterUndo("Color Change", mWidget);
            mWidget.color = color;
        }
    }
Ejemplo n.º 45
0
	/// <summary>
	/// Labels used for input shouldn't support rich text.
	/// </summary>

	protected void Init ()
	{
		if (mDoInit && label != null)
		{
			mDoInit = false;
			mDefaultText = label.text;
			mDefaultColor = label.color;
			label.supportEncoding = false;
			mPivot = label.pivot;
			mPosition = label.cachedTransform.localPosition.x;
			UpdateLabel();
		}
	}
Ejemplo n.º 46
0
        public float GetMinMaxOffset(Vector3 size, UIWidget.Pivot pivot, ref float boundsMin, ref float boundsMax)
        {
            if (null == panel)
            {
                return(0);
            }
            boundsMin = boundsMax = 0;
            float space = 0;

            switch (movement)
            {
            case Movement.Horizontal:
            {
                Vector4 clipRegion   = panel.baseClipRegion;
                Vector2 clipSoftness = panel.clipSoftness;
                space = size.x - clipRegion.z;
                switch (pivot)
                {
                case UIWidget.Pivot.Left:
                case UIWidget.Pivot.TopLeft:
                case UIWidget.Pivot.BottomLeft:
                {
                    if (space < 0)
                    {
                        boundsMin = -clipRegion.z * 0.5f + clipSoftness.x;
                        boundsMax = -boundsMin;
                    }
                    else
                    {
                        boundsMax = -clipRegion.z * 0.5f + clipSoftness.x;
                        boundsMin = boundsMax - space - (clipSoftness.x * 2f);
                    }
                }
                break;

                case UIWidget.Pivot.Center:
                case UIWidget.Pivot.Top:
                case UIWidget.Pivot.Bottom:
                {
                    if (space < 0)
                    {
                        boundsMin = space * 0.5f + clipSoftness.x;
                        boundsMax = -boundsMin;
                    }
                    else
                    {
                        boundsMax = space * 0.5f + clipSoftness.x;
                        boundsMin = -boundsMax;
                    }
                }
                break;

                default:
                    Debug.LogError("ScrollViewport[" + mTrans.parent.name + "]can only use center with context pivot!");
                    break;
                }
            }
            break;

            case Movement.Vertical:
            {
                Vector4 clipRegion   = panel.baseClipRegion;
                Vector2 clipSoftness = panel.clipSoftness;
                space = size.y - clipRegion.w;
                switch (pivot)
                {
                case UIWidget.Pivot.Top:
                case UIWidget.Pivot.TopRight:
                case UIWidget.Pivot.TopLeft:
                {
                    if (space < 0)
                    {
                        boundsMin = -clipRegion.w * 0.5f + clipSoftness.y;
                        boundsMax = -boundsMin;
                    }
                    else
                    {
                        boundsMin = clipRegion.w * 0.5f - clipSoftness.y;
                        boundsMax = boundsMin + space + (clipSoftness.y * 2f);
                    }
                }
                break;

                case UIWidget.Pivot.Center:
                case UIWidget.Pivot.Left:
                case UIWidget.Pivot.Right:
                {
                    if (space < 0)
                    {
                        boundsMax = -space * 0.5f - clipSoftness.y;
                        boundsMin = -boundsMax;
                    }
                    else
                    {
                        boundsMin = -space * 0.5f - clipSoftness.y;
                        boundsMax = -boundsMin;
                    }
                }
                break;

                default:
                    Debug.LogError("ScrollViewport[" + mTrans.parent.name + "]can only use center with context pivot!");
                    break;
                }
            }
            break;
            }
            return(space);
        }
Ejemplo n.º 47
0
	/// <summary>
	/// Cache the transform and the panel.
	/// </summary>

	void Awake ()
	{
		mTrans = transform;
		mPanel = GetComponent<UIPanel>();

		if (mPanel.clipping == UIDrawCall.Clipping.None)
			mPanel.clipping = UIDrawCall.Clipping.ConstrainButDontClip;
		
		// Auto-upgrade
		if (movement != Movement.Custom && scale.sqrMagnitude > 0.001f)
		{
			if (scale.x == 1f && scale.y == 0f)
			{
				movement = Movement.Horizontal;
			}
			else if (scale.x == 0f && scale.y == 1f)
			{
				movement = Movement.Vertical;
			}
			else if (scale.x == 1f && scale.y == 1f)
			{
				movement = Movement.Unrestricted;
			}
			else
			{
				movement = Movement.Custom;
				customMovement.x = scale.x;
				customMovement.y = scale.y;
			}
			scale = Vector3.zero;
#if UNITY_EDITOR
			NGUITools.SetDirty(this);
#endif
		}

		// Auto-upgrade
		if (contentPivot == UIWidget.Pivot.TopLeft && relativePositionOnReset != Vector2.zero)
		{
			contentPivot = NGUIMath.GetPivot(new Vector2(relativePositionOnReset.x, 1f - relativePositionOnReset.y));
			relativePositionOnReset = Vector2.zero;
#if UNITY_EDITOR
			NGUITools.SetDirty(this);
#endif
		}
	}
Ejemplo n.º 48
0
        public void ScrollNotChcekBounds(float pos, Vector3 size, UIWidget.Pivot pivot)
        {
            if (null == panel)
            {
                return;
            }
            float boundsMin = 0, boundsMax = 0;
            float space = GetMinMaxOffset(size, pivot, ref boundsMin, ref boundsMax);

            switch (movement)
            {
            case Movement.Horizontal:
            {
                Vector3 oriPos       = transform.localPosition;
                Vector2 clipOffset   = panel.clipOffset;
                Vector2 clipSoftness = panel.clipSoftness;
                Vector4 clipRange    = panel.baseClipRegion;
                float   offPos       = oriPos.x + clipOffset.x;
                oriPos.x = offPos + pos;
                if (size.x != 0)
                {
                    switch (pivot)
                    {
                    case UIWidget.Pivot.Left:
                    case UIWidget.Pivot.TopLeft:
                    case UIWidget.Pivot.BottomLeft:
                    {
                        boundsMax = -clipRange.z * 0.5f + clipSoftness.x;
                        boundsMin = boundsMax - space - (clipSoftness.x * 2f);
                    }
                    break;

                    case UIWidget.Pivot.Center:
                    case UIWidget.Pivot.Top:
                    case UIWidget.Pivot.Bottom:
                    {
                        boundsMax = space * 0.5f + clipSoftness.x;
                        boundsMin = -boundsMin;
                    }
                    break;

                    case UIWidget.Pivot.Right:
                    case UIWidget.Pivot.TopRight:
                    case UIWidget.Pivot.BottomRight:
                    {
                        boundsMin = clipRange.z * 0.5f - clipSoftness.x;
                        boundsMax = boundsMin + space + (clipSoftness.x * 2f);
                    }
                    break;
                    }
                    if (oriPos.x < boundsMin)
                    {
                        oriPos.x = boundsMin;
                    }
                    else if (oriPos.x > boundsMax)
                    {
                        oriPos.x = boundsMax;
                    }
                }
                transform.localPosition = oriPos;
                clipOffset.x            = -(oriPos.x - offPos);
                clipOffset.y            = 0;
                panel.clipOffset        = clipOffset;
            }
            break;

            case Movement.Vertical:
            {
                Vector3 oriPos       = transform.localPosition;
                Vector2 clipOffset   = panel.clipOffset;
                Vector2 clipSoftness = panel.clipSoftness;
                Vector4 clipRange    = panel.baseClipRegion;
                float   offPos       = oriPos.y + clipOffset.y;
                oriPos.y = offPos - pos;
                if (size.y != 0)
                {
                    switch (pivot)
                    {
                    case UIWidget.Pivot.Top:
                    case UIWidget.Pivot.TopRight:
                    case UIWidget.Pivot.TopLeft:
                    {
                        boundsMin = clipRange.w * 0.5f - clipSoftness.y;
                        boundsMax = boundsMin + space + (clipSoftness.y * 2f);
                    }
                    break;

                    case UIWidget.Pivot.Center:
                    case UIWidget.Pivot.Left:
                    case UIWidget.Pivot.Right:
                    {
                        boundsMin = -space * 0.5f - clipSoftness.y;
                        boundsMax = -boundsMin;
                    }
                    break;

                    case UIWidget.Pivot.Bottom:
                    case UIWidget.Pivot.BottomRight:
                    case UIWidget.Pivot.BottomLeft:
                    {
                        boundsMax = -clipRange.w * 0.5f + clipSoftness.y;
                        boundsMin = boundsMax - space - (clipSoftness.y * 2f);
                    }
                    break;
                    }
                    if (oriPos.y < boundsMin)
                    {
                        oriPos.y = boundsMin;
                    }
                    else if (oriPos.y > boundsMax)
                    {
                        oriPos.y = boundsMax;
                    }
                }
                transform.localPosition = oriPos;
                clipOffset.x            = 0;
                clipOffset.y            = -(oriPos.y - offPos);
                panel.clipOffset        = clipOffset;
            }
            break;
            }
            UpdateScrollbars(false);
        }